General Computation Methods as Higher-Order Functions
Learn how to define general computation methods using higher-order functions.
So far, we’ve mainly defined functions whose arguments or return values are numbers, boolean values, or strings. But recall that functions are first-class citizens in functional programming languages. Thanks to this, we can easily define a function that accepts other functions as arguments or returns another function as a result. Such a function is called a higher-order function. High-order functions are powerful because they enable us to formulate computation patterns that work with different functions.
Summation as a higher-order function
A good way to appreciate the power of functions operating on other functions is to look at summation in mathematics. For instance, mathematicians often study summations, sums of a sequence of numbers, like the sum of all natural numbers from 1 to :
Or the sum of squares of natural numbers from 1 to :
If we look at these sums of sequences, we can notice that summation can be defined for any function capable of producing the terms for the sum. Of course, mathematicians realized this a long time ago. They invented the summation symbol (read “sigma”) to express the sum of elements represented by a function within an interval, .
The following diagram illustrates how the concept of summation is a generalization of more concrete sum concepts:
Get hands-on with 1200+ tech skills courses.