Higher-order functions
Another important concept that appears in functional programming is that of higher-order functions. A higher-order function is a function that accepts a function as an argument. A very trivial example of where this may be useful is control structures. For example, a while
loop can be expressed in a functional way as a higher-order function that accepts the body of the loop and a predicate as an argument.
The body of the loop can be expressed as a function that does not accept any arguments, but computes some side effects. The way it works is that we have a function accept a 0-argument
function and a predicate, and we call the same loop
function recursively while the predicate is true.
We can call the new control structure whileDiy
, and it can be defined as follows:
@annotation.tailrec def whileDiy(predicate: => Boolean)(body: => Unit): Unit = if (predicate) { body whileDiy(predicate)(body) } }
The whileDiy
construct accepts a predicate and a body. The...