Member-only story
Introduction to Higher-Order Functions
Understanding higher-order functions like map, filter, and reduce with examples
Higher-Order Functions
A higher-order function is a function that accepts another function as a parameter or returns a function as its return type. The easiest way to understand this is by realizing that functions can be treated just like any other piece of data.
In languages that support higher-order functions, much like you would with a String
or Integer
, you can pass functions as parameters, store them, and return them.
Anonymous Functions
Before exploring higher-order functions, it is first important to cover anonymous functions, which are often used alongside higher-order functions.
An anonymous function, or lambda, is simply a function that was declared without any named identifier to refer to it. They can still be stored in variables and therefore can still be named within the code, but the function itself is declared without a name attached.
For example, in Java, a simple anonymous function looks like this:
x -> x + 1
The input of this function is x
, and the output is x + 1
.
Syntax for anonymous functions varies slightly across languages, but it is typically written in the form of (inputs) → (output).
Anonymous functions are often used because they avoid the boilerplate code associated with formally declaring them as named functions. So, for simple functions that may not be used in more than one place, such as the above, it may be more appropriate to use an anonymous function.
Example
Now, we will go into a very basic example of a higher-order function that uses anonymous functions. This example uses Python, where the syntax for anonymous functions is lambda (inputs): (output)
.
def add_n(n):
return lambda x: x + n
This example takes a number n
and returns a function that adds n
to the input.
So, if we wanted to add 1 + 2, we could do that by calling add_n(2)(1)
. The first call, add_n(2)
, returns a function…