⏸️What are Higher-Order Functions Used For?

What's the point?

Yeah, alright, higher-order functions are cool and stuff. But what are they used for?

The higher-ordering of a function can be thought of as maintaining a layer of memory outside of a given function. Consider this example:

def f(x):
    def g(y):
        return x + y
    return g

func = f(3)

Now, func has some memory, some data it can use, beyond just the y that can be passed into it as an argument. It has a way of remembering the x that was passed in to create it. This is the power of higher-order functions.

Not only can be store these external to the function values, we can develop ways to update them too. For example, consider a function that takes in an argument x, which is the number of times the function is allowed to run, and returns a fucntion. Calls to this function print the value passed in. Any more calls than the number x, and the function should print the string "Nope!" instead. This function returns another function that does the same thing.

You might immediately pick up on the fact that this cannot be done through just one layer of function β€” there is some information that needs to be retained across function calls. Higher-order functions allow us to do this.

def f(x):
    def g(y):
        if x <= 0:
            print("Nope!")
        else:
            print(y)
        ...
    return g

As you might be able to tell from the ... in the code, this function is not yet complete. While f returns g properly, what we haven't figured out yet is a way to decrement x when a function call happens. We know that g is supposed to essentially return another g. However, adding the line return g does not fix the updating the value of x problem. Is there a way we can do both?

You bet there is.

def f(x):
    def g(y):
        if x <= 0:
            print("Nope!")
        else:
            print(y)
        return f(x-1)
    return g

What we've uncovered here is the general structure of many higher-order functions: where the inner function calls the outer one and the outer function returns the inner one.

Last updated