What are higher order functions?

These are the functions which takes one or more functions  as an argument and returns a function. As an example, lets see a simple code.

def speed(n):
    return 'fast' if n < 3 else 'slow'

def run(func, speed):
    return f'Runing {func(speed)}'

speed1 = run(speed, 2)
speed2 = run(speed, 5)

print(speed1)
print(speed2)
# -> Running fast
# -> Running slow
  • The speed(n) function takes a number n as input and returns the string ‘fast’ if n is less than 3, and ‘slow’ otherwise. This function defines a mapping between the input n and the corresponding running speed.
  • The run(func, speed) function takes two arguments, func and speed. func is a function that takes an integer as input and returns a string, and speed is an integer that represents the running speed. run() calls func(speed) to get the corresponding string representation of the speed, and returns a formatted string that says “Running string representation of the speed“.

The above example demonstrates the use of higher-order functions in Python. The run() function takes a function (speed() in this case) as an argument and uses it to compute a result. This allows the function to be more flexible and reusable, as it can work with different functions that have the same input and output types.

 

In python, there are some predefined higher order functions like map() reduce() and filter() we will look at these functions in another section.

Leave a Reply

Your email address will not be published. Required fields are marked *