In mathematics and computer science, a higher-order function (HOF) is a function that does at least one of the following:
All other functions are first-order functions. In mathematics higher-order functions are also termed operators or functionals. The differential operator in calculus is a common example, since it maps a function to its derivative, also a function. Higher-order functions should not be confused with other uses of the word "functor" throughout mathematics, see Functor (disambiguation).
In the untyped lambda calculus, all functions are higher-order; in a typed lambda calculus, from which most functional programming languages are derived, higher-order functions that take one function as argument are values with types of the form
(\tau1\to\tau2)\to\tau3
[[map (higher-order function)|map]]
function, found in many functional programming languages, is one example of a higher-order function. It takes as arguments a function f and a collection of elements, and as the result, returns a new collection with f applied to each element from the collection.qsort
is an example of this.The examples are not intended to compare and contrast programming languages, but to serve as examples of higher-order function syntax
In the following examples, the higher-order function takes a function, and applies the function to some value twice. If has to be applied several times for the same it preferably should return a function rather than a value. This is in line with the "don't repeat yourself" principle.
plusthree←
g← g 713
Or in a tacit manner:
plusthree←+∘3
g←plusthree twice g 713
Using in C++11:
auto twice = [](const std::function
auto plus_three = [](int i)
int main
Or, with generic lambdas provided by C++14:
auto twice = [](const auto& f)
auto plus_three = [](int i)
int main
Using just delegates:
public class Program
Or equivalently, with static methods:
public class Program
(defn plus-three [i] (+ i 3))
(def g (twice plus-three))
(println (g 7)) ; 13
plusThree = function(i) ;
g = twice(plusThree);
writeOutput(g(7)); // 13
alias twice = (f) => (int x) => f(f(x));
alias plusThree = (int i) => i + 3;
void main
int plusThree(int i)
void main
In Elixir, you can mix module definitions and anonymous functions
plus_three = fn(i) -> i + 3 end
g = Hof.twice(plus_three)
IO.puts g.(7) # 13
Alternatively, we can also compose using pure anonymous functions.
plus_three = fn(i) -> i + 3 end
g = twice.(plus_three)
IO.puts g.(7) # 13
or_else(Fs, X, false) -> or_else(Fs, X);or_else(Fs, _,) -> or_else(Fs, Y);or_else(_, _, R) -> R.
or_else([fun erlang:is_integer/1, fun erlang:is_atom/1, fun erlang:is_list/1], 3.23).
In this Erlang example, the higher-order function takes a list of functions and argument . It evaluates the function with the argument as argument. If the function returns false then the next function in will be evaluated. If the function returns then the next function in with argument will be evaluated. If the function returns the higher-order function will return . Note that,, and can be functions. The example returns .
let plus_three = (+) 3
let g = twice plus_three
g 7 |> printf "%A" // 13
import "fmt"
func twice(f func(int) int) func(int) int
func main
Notice a function literal can be defined either with an identifier or anonymously (assigned to variable).
plusThree :: Int -> IntplusThree = (+3)
main :: IO main = print (g 7) -- 13 where g = twice plusThree
Explicitly,
plusthree=. verb : 'y + 3' g=. plusthree twice g 713
or tacitly,
plusthree=. +&3 g=. plusthree twice g 713
Using just functional interfaces:
class Main
Or equivalently, with static methods:
class Main
With arrow functions:
const twice = f => x => f(f(x));
const plusThree = i => i + 3;
const g = twice(plusThree);
console.log(g(7)); // 13
Or with classical syntax:
function twice(f)
function plusThree(i)
const g = twice(plusThree);
console.log(g(7)); // 13
julia> plusthree(i) = i + 3plusthree (generic function with 1 method)
julia> g = twice(plusthree)(::var"#result#3") (generic function with 1 method)
julia> g(7)13
fun plusThree(i: Int) = i + 3
fun main
function plusThree(i) return i + 3end
local g = twice(plusThree)
print(g(7)) -- 13
plusthree = @(i) i + 3;
g = twice(plusthree)
disp(g(7)); % 13
let plus_three = (+) 3
let = let g = twice plus_three in
print_int (g 7); (* 13 *) print_newline
declare(strict_types=1); function twice(callable $f): Closure function plusThree(int $i): int $g = twice('plusThree'); echo $g(7), "\n"; // 13
or with all functions in variables:
declare(strict_types=1); $twice = fn(callable $f): Closure => fn(int $x): int => $f($f($x)); $plusThree = fn(int $i): int => $i + 3; $g = $twice($plusThree); echo $g(7), "\n"; // 13
Note that arrow functions implicitly capture any variables that come from the parent scope,[1] whereas anonymous functions require the keyword to do the same.
sub twice
sub plusThree
my $g = twice(\&plusThree);
print $g->(7), "\n"; # 13
or with all functions in variables:
my $twice = sub ;
my $plusThree = sub ;
my $g = $twice->($plusThree);
print $g->(7), "\n"; # 13
>>> plus_three = lambda i: i + 3
>>> g = twice(plus_three) >>> g(7)13
Python decorator syntax is often used to replace a function with the result of passing that function through a higher-order function. E.g., the function could be implemented equivalently:
>>> g(7)13
plusThree <- function(i)
g <- twice(plusThree)
> print(g(7))[1] 13
sub plusThree(Int:D $i)
my $g = twice(&plusThree);
say $g(7); # 13
In Raku, all code objects are closures and therefore can reference inner "lexical" variables from an outer scope because the lexical variable is "closed" inside of the function. Raku also supports "pointy block" syntax for lambda expressions which can be assigned to a variable or invoked anonymously.
plus_three = ->(i)
g = twice(plus_three)
puts g.call(7) # 13
fn plus_three(i: i32) -> i32
fn main
(define (twice f) (compose f f))
(define (plus-three i) (+ i 3))
(define g (twice plus-three))
(display (g 7)) ; 13(display "\n")
let plusThree =
let g = twice(plusThree)
print(g(7)) // 13
puts [apply $twice $plusThree 7]
Tcl uses apply command to apply an anonymous function (since 8.6).
The XACML standard defines higher-order functions in the standard to apply a function to multiple values of attribute bags.
The list of higher-order functions in XACML can be found here.
declare function local:plusthree($i) ;
local:twice(local:plusthree#1, 7) (: 13 :)
Function pointers in languages such as C, C++, Fortran, and Pascal allow programmers to pass around references to functions. The following C code computes an approximation of the integral of an arbitrary function:
double square(double x)
double cube(double x)
/* Compute the integral of f within the interval [a,b] */double integral(double f(double x), double a, double b, int n)
int main
The qsort function from the C standard library uses a function pointer to emulate the behavior of a higher-order function.
Macros can also be used to achieve some of the effects of higher-order functions. However, macros cannot easily avoid the problem of variable capture; they may also result in large amounts of duplicated code, which can be more difficult for a compiler to optimize. Macros are generally not strongly typed, although they may produce strongly typed code.
In other imperative programming languages, it is possible to achieve some of the same algorithmic results as are obtained via higher-order functions by dynamically executing code (sometimes called Eval or Execute operations) in the scope of evaluation. There can be significant drawbacks to this approach:
In object-oriented programming languages that do not support higher-order functions, objects can be an effective substitute. An object's methods act in essence like functions, and a method may accept objects as parameters and produce objects as return values. Objects often carry added run-time overhead compared to pure functions, however, and added boilerplate code for defining and instantiating an object and its method(s). Languages that permit stack-based (versus heap-based) objects or structs can provide more flexibility with this method.
An example of using a simple stack based record in Free Pascal with a function that returns a function:
type int = integer; Txy = record x, y: int; end; Tf = function (xy: Txy): int; function f(xy: Txy): int; begin Result := xy.y + xy.x; end;
function g(func: Tf): Tf; begin result := func; end;
var a: Tf; xy: Txy = (x: 3; y: 7);
begin a := g(@f); // return a function to "a" writeln(a(xy)); // prints 10end.
The function a
takes a Txy
record as input and returns the integer value of the sum of the record's x
and y
fields (3 + 7).
Defunctionalization can be used to implement higher-order functions in languages that lack first-class functions:
// Defunctionalized function application implementationstemplate
template
template
// Higher-order compose functiontemplate
int main(int argc, const char* argv[])
In this case, different types are used to trigger different functions via function overloading. The overloaded function in this example has the signature auto apply
.