Higher Order Function

November 21 2024

A function is said to be a Higher-Order Function if it takes other functions as arguments or returns a function as an output. It is closely related to the concept of functional programming.

Examples to illustrate the concept of Higher Order Function:

The above code is a custom map function in Python called custom_map. The function two arguments:

  • func: a function that will be applied to each element of the input list.
  • args_list: a list of arguments to apply the function func to.

The custom_map function generates an empty list called result and then iterates through the args_list. The func function is applied to each element in the args_list, and the result is added to the result list. Finally, the result list is returned. In this example, the list [1, 2, 3, 4, 5] and the square function are both passed as the first and second arguments, respectively, to custom_map. The custom_map function creates a new list containing the squares of each element in the input list because the square function just returns the square of its argument:
[1, 4, 9, 16, 25]

So, when the code is executed, the output will be:
[1, 4, 9, 16, 25]

In this example, custom_map is a Higher-Order Function that takes a function(square function in the above example) and an iterables.

The concise and efficient code for the above example is as follows:

def square(x):
      return x*x
print(list(map(square, [1, 2, 3, 4, 5])))


Similarly,  in this concise code, map is a Higher-Order Function that takes a function(square function in the above example) and an iterable.