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:
return x + y
func = f(3)
funchas some memory, some data it can use, beyond just the
ythat can be passed into it as an argument. It has a way of remembering the
xthat 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.
if x <= 0:
As you might be able to tell from the
...in the code, this function is not yet complete. While
gproperly, what we haven't figured out yet is a way to decrement
xwhen a function call happens. We know that
gis supposed to essentially return another
g. However, adding the line
return gdoes not fix the updating the value of
xproblem. Is there a way we can do both?
You bet there is.
if x <= 0:
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.