Higher-order functions take other functions as arguments and/or return them as results. They form the building blocks of functional programming. Most functional languages have some form of filter function, for example. This is a higher-order function, taking a list and a predicate (function that returns true or false) as arguments.
Functions that do neither of these are often referred to as first-order functions
.
function validate(number,predicate) {
if (predicate) { // Is Predicate defined
return predicate(number);
}
return false;
}
Here "predicate" is a function that will test for some condition involving its arguments and return true or false.
An example call for the above is:
validate(someNumber, function(arg) {
return arg % 10 == 0;
}
);
A common requirement is to add numbers within a range. By using higher-order functions we can extend this basic capability, applying a transformation function on each number before including it in the sum.
You want to add all integers within a given range (using Scala)
def sumOfInts(a: Int, b: Int): Int = {
if(a > b) 0
else a + sumOfInts(a+1, b)
}
You want to add squares of all integers within a given range
def square(a: Int): Int = a * a
def sumOfSquares(a: Int, b: Int): Int = {
if(a > b) 0
else square(a) + sumOfSquares(a + 1, b)
}
Notice these things have 1 thing in common, that you want to apply a function on each argument and then add them.
Lets create a higher-order function to do both:
def sumHOF(f: Int => Int, a: Int, b: Int): Int = {
if(a > b) 0
else f(a) + sumHOF(f, a + 1, b)
}
You can call it like this:
def identity(a: Int): Int = a
def square(a: Int): Int = a * a
Notice that sumOfInts
and sumOfSquare
can be defined as:
def sumOfInts(a: Int, b: Int): Int = sumHOF(identity, a, b)
def sumOfSquares(a: Int, b: Int): Int = sumHOF(square, a, b)
As you can see from this simple example, higher-order functions provide more generalized solutions and reducing code duplication.
I have used Scala By Example - by Martin Odersky as a reference.