General Computation Methods as Higher-Order Functions
Explore how higher-order functions allow you to generalize computation methods such as summation and accumulation in functional programming. Understand the abstraction hierarchy from concrete sums and products to flexible higher-order functions like accumulate. Learn to apply this powerful concept using OCaml to reduce code duplication and raise your programming abstraction level.
We'll cover the following...
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 :
...