Higher Order Functions

Written by Harnoor Chima (10/4/20)

Introduction

A function can be called a higher order function when it can take other functions as a parameter or gives a function as an output. Combining the applications of two functions opens up many more options for problem solving in the programs we create. In short, higher order functions can be described as a function (or functions) that operates with another function.

Functions as Objects

In Python, functions can be stored inside of a variable and be used in the same way as they would be normally.

def shout(text):
    return text.upper()
    
print(shout("Hey"))

yell = shout

print(yell("Hey"))

Output:
HEY
HEY

In this example we can see that the function can be assigned to any variable and still have the same effect. Whether we use the original name of the function 'shout' or reassign it to a new variable it will still give the same output of all uppercase text.

Passing a Function as an Argument

Since functions are objects in Python, we can pass them as arguments into other functions to open up more options by combining their uses.

def shout(text):
    return text.upper()

def whisper(text):
    return text.lower()

def greet(func):
    greeting = func("This is a string, 
    created by a function")
    print(greeting)
    
greet(shout)
greet(whisper)

In this example we define a function that takes another function as an argument where 'shout' and 'whisper are the functions being taken as arguments. 'func' is a placeholder for the functions 'shout' and 'whisper' which will be applied to the string.

Returning a Function through a Function

We can use the idea of higher order functions to create a function that returns another function that runs a set of code.

def create_multiplier(x):
    def multiplier(y):
        return x*y
    
    return multiplier

multiplyBy_3 = create_multiplier(3)

print(multiplyBy_3(5))

In this example, we create an initial function that will make a new function that will multiply by whatever number we set x to. The function created here will multiply the argument of the create_multiplier by the number 3.

Conclusion

The concept of higher order functions is primarily used to construct new more complex functions that will allow us to have programs with a lot more functionality than before.

Last updated