Hubbry Logo
Higher-order functionHigher-order functionMain
Open search
Higher-order function
Community hub
Higher-order function
logo
7 pages, 0 posts
0 subscribers
Be the first to start a discussion here.
Be the first to start a discussion here.
Contribute something
Higher-order function
Higher-order function
from Wikipedia

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 .

General examples

[edit]
  • map function, found in many functional programming languages, is one example of a higher-order function. It takes arguments as 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.
  • sort, which take a comparison function as a parameter, allowing the programmer to separate the sorting algorithm from the comparisons of the items being sorted. The C standard function qsort is an example of this.
  • filter
  • fold (including foldl and foldr)
  • scan
  • apply
  • Function composition
  • Integration
  • Callback
  • Tree traversal
  • Montague grammar, a semantic theory of natural language, uses higher-order functions

Support in programming languages

[edit]

Direct support

[edit]

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 twice takes a function, and applies the function to some value twice. If twice has to be applied several times for the same f it preferably should return a function rather than a value. This is in line with the "don't repeat yourself" principle.

APL

[edit]
      twice{⍺⍺ ⍺⍺ }

      plusthree{+3}

      g{plusthree twice }
    
      g 7
13

Or in a tacit manner:

      twice2

      plusthree+3

      gplusthree twice
    
      g 7
13

C++

[edit]

Using std::function in C++11:

import std;

auto twice = [](const std::function<int(int)>& f) -> auto {
    return [f](int x) -> int {
        return f(f(x));
    };
};

auto plusThree = [](int i) -> int {
    return i + 3;
};

int main() {
    auto g = twice(plusThree);

    std::println("{}", g(7)); // 13
}

Or, with generic lambdas provided by C++14:

import std;

auto twice = [](const auto& f) -> auto {
    return [f](int x) -> int {
        return f(f(x));
    };
};

auto plusThree = [](int i) -> int {
    return i + 3;
};

int main() {
    auto g = twice(plusThree);

    std::println("{}", g(7)); // 13
}

C#

[edit]

Using just delegates:

using System;

public class Program
{
    public static void Main(string[] args)
    {
        Func<Func<int, int>, Func<int, int>> twice = f => x => f(f(x));

        Func<int, int> plusThree = i => i + 3;

        var g = twice(plusThree);

        Console.WriteLine(g(7)); // 13
    }
}

Or equivalently, with static methods:

using System;

public class Program
{
    private static Func<int, int> Twice(Func<int, int> f)
    {
        return x => f(f(x));
    }

    private static int PlusThree(int i) => i + 3;

    public static void Main(string[] args)
    {
        var g = Twice(PlusThree);

        Console.WriteLine(g(7)); // 13
    }
}

Clojure

[edit]
(defn twice [f]
  (fn [x] (f (f x))))

(defn plus-three [i]
  (+ i 3))

(def g (twice plus-three))

(println (g 7)) ; 13

ColdFusion Markup Language (CFML)

[edit]
twice = function(f) {
    return function(x) {
        return f(f(x));
    };
};

plusThree = function(i) {
    return i + 3;
};

g = twice(plusThree);

writeOutput(g(7)); // 13

Common Lisp

[edit]
(defun twice (f)                                                                
  (lambda (x) (funcall f (funcall f x))))                                       
                                                                                
(defun plus-three (i)                                                           
  (+ i 3))                                                                      
                                                                                
(defvar g (twice #'plus-three))                                                 
                                                                                
(print (funcall g 7))

D

[edit]
import std.stdio : writeln;

alias twice = (f) => (int x) => f(f(x));

alias plusThree = (int i) => i + 3;

void main()
{
    auto g = twice(plusThree);

    writeln(g(7)); // 13
}

Dart

[edit]
int Function(int) twice(int Function(int) f) {
    return (x) {
        return f(f(x));
    };
}

int plusThree(int i) {
    return i + 3;
}

void main() {
    final g = twice(plusThree);
    
    print(g(7)); // 13
}

Elixir

[edit]

In Elixir, you can mix module definitions and anonymous functions

defmodule Hof do
    def twice(f) do
        fn(x) -> f.(f.(x)) end
    end
end

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.

twice = fn(f) ->
    fn(x) -> f.(f.(x)) end
end

plus_three = fn(i) -> i + 3 end

g = twice.(plus_three)

IO.puts g.(7) # 13

Erlang

[edit]
or_else([], _) -> false;
or_else([F | Fs], X) -> or_else(Fs, X, F(X)).

or_else(Fs, X, false) -> or_else(Fs, X);
or_else(Fs, _, {false, Y}) -> 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 or_else/2 takes a list of functions (Fs) and argument (X). It evaluates the function F with the argument X as argument. If the function F returns false then the next function in Fs will be evaluated. If the function F returns {false, Y} then the next function in Fs with argument Y will be evaluated. If the function F returns R the higher-order function or_else/2 will return R. Note that X, Y, and R can be functions. The example returns false.

F#

[edit]
let twice f = f >> f

let plus_three = (+) 3

let g = twice plus_three

g 7 |> printf "%A" // 13

Go

[edit]
package main

import "fmt"

func twice(f func(int) int) func(int) int {
	return func(x int) int {
		return f(f(x))
	}
}

func main() {
	plusThree := func(i int) int {
		return i + 3
	}

	g := twice(plusThree)

	fmt.Println(g(7)) // 13
}

Notice a function literal can be defined either with an identifier (twice) or anonymously (assigned to variable plusThree).

Groovy

[edit]
def twice = { f, x -> f(f(x)) }
def plusThree = { it + 3 }
def g = twice.curry(plusThree) 
println g(7) // 13

Haskell

[edit]
twice :: (Int -> Int) -> (Int -> Int)
twice f = f . f

plusThree :: Int -> Int
plusThree = (+3)

main :: IO ()
main = print (g 7) -- 13
  where
    g = twice plusThree

J

[edit]

Explicitly,

   twice=.     adverb : 'u u y'

   plusthree=. verb   : 'y + 3'
   
   g=. plusthree twice
   
   g 7
13

or tacitly,

   twice=. ^:2

   plusthree=. +&3
   
   g=. plusthree twice
   
   g 7
13

Java (1.8+)

[edit]

Using just functional interfaces:

import java.util.function.*;

class Main {
    public static void main(String[] args) {
        Function<IntUnaryOperator, IntUnaryOperator> twice = f -> f.andThen(f);

        IntUnaryOperator plusThree = i -> i + 3;

        var g = twice.apply(plusThree);

        System.out.println(g.applyAsInt(7)); // 13
    }
}

Or equivalently, with static methods:

import java.util.function.*;

class Main {
    private static IntUnaryOperator twice(IntUnaryOperator f) {
        return f.andThen(f);
    }

    private static int plusThree(int i) {
        return i + 3;
    }

    public static void main(String[] args) {
        var g = twice(Main::plusThree);

        System.out.println(g.applyAsInt(7)); // 13
    }
}

JavaScript

[edit]

With arrow functions:

"use strict";

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:

"use strict";

function twice(f) {
  return function (x) {
    return f(f(x));
  };
}

function plusThree(i) {
  return i + 3;
}

const g = twice(plusThree);

console.log(g(7)); // 13

Julia

[edit]
julia> function twice(f)
           function result(x)
               return f(f(x))
           end
           return result
       end
twice (generic function with 1 method)

julia> plusthree(i) = i + 3
plusthree (generic function with 1 method)

julia> g = twice(plusthree)
(::var"#result#3"{typeof(plusthree)}) (generic function with 1 method)

julia> g(7)
13

Kotlin

[edit]
fun twice(f: (Int) -> Int): (Int) -> Int {
    return { f(f(it)) }
}

fun plusThree(i: Int) = i + 3

fun main() {
    val g = twice(::plusThree)

    println(g(7)) // 13
}

Lua

[edit]
function twice(f)
  return function (x)
    return f(f(x))
  end
end

function plusThree(i)
  return i + 3
end

local g = twice(plusThree)

print(g(7)) -- 13

MATLAB

[edit]
function result = twice(f)
result = @(x) f(f(x));
end

plusthree = @(i) i + 3;

g = twice(plusthree)

disp(g(7)); % 13

OCaml

[edit]
let twice f x =
  f (f x)

let plus_three =
  (+) 3

let () =
  let g = twice plus_three in

  print_int (g 7); (* 13 *)
  print_newline ()

PHP

[edit]
<?php

declare(strict_types=1);

function twice(callable $f): Closure {
    return function (int $x) use ($f): int {
        return $f($f($x));
    };
}

function plusThree(int $i): int {
    return $i + 3;
}

$g = twice('plusThree');

echo $g(7), "\n"; // 13

or with all functions in variables:

<?php

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 use keyword to do the same.

Perl

[edit]
use strict;
use warnings;

sub twice {
    my ($f) = @_;
    sub {
        $f->($f->(@_));
    };
}

sub plusThree {
    my ($i) = @_;
    $i + 3;
}

my $g = twice(\&plusThree);

print $g->(7), "\n"; # 13

or with all functions in variables:

use strict;
use warnings;

my $twice = sub {
    my ($f) = @_;
    sub {
        $f->($f->(@_));
    };
};

my $plusThree = sub {
    my ($i) = @_;
    $i + 3;
};

my $g = $twice->($plusThree);

print $g->(7), "\n"; # 13

Python

[edit]
def twice(f: Callable[Any]) -> Any:
    def result(x: Any) -> Any:
        return f(f(x))
    return result

plus_three: Callable[int] = lambda i: i + 3

g: int = twice(plus_three)
    
print(g(7))
# prints 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 g could be implemented equivalently:

@twice
def g(i: int) -> int:
    return i + 3

print(g(7))
# prints 13

R

[edit]
twice <- \(f) \(x) f(f(x))

plusThree <- function(i) i + 3

g <- twice(plusThree)

> g(7)
[1] 13

Raku

[edit]
sub twice(Callable:D $f) {
    return sub { $f($f($^x)) };
}

sub plusThree(Int:D $i) {
    return $i + 3;
}

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.

Ruby

[edit]
def twice(f)
  ->(x) { f.call(f.call(x)) }
end

plus_three = ->(i) { i + 3 }

g = twice(plus_three)

puts g.call(7) # 13

Rust

[edit]
fn twice(f: impl Fn(i32) -> i32) -> impl Fn(i32) -> i32 {
    move |x| f(f(x))
}

fn plus_three(i: i32) -> i32 {
    i + 3
}

fn main() {
    let g = twice(plus_three);

    println!("{}", g(7)) // 13
}

Scala

[edit]
object Main {
  def twice(f: Int => Int): Int => Int =
    f compose f

  def plusThree(i: Int): Int =
    i + 3

  def main(args: Array[String]): Unit = {
    val g = twice(plusThree)

    print(g(7)) // 13
  }
}

Scheme

[edit]
(define (compose f g) 
  (lambda (x) (f (g x))))

(define (twice f) 
  (compose f f))

(define (plus-three i)
  (+ i 3))

(define g (twice plus-three))

(display (g 7)) ; 13
(display "\n")

Swift

[edit]
func twice(_ f: @escaping (Int) -> Int) -> (Int) -> Int {
    return { f(f($0)) }
}

let plusThree = { $0 + 3 }

let g = twice(plusThree)

print(g(7)) // 13

Tcl

[edit]
set twice {{f x} {apply $f [apply $f $x]}}
set plusThree {{i} {return [expr $i + 3]}}

# result: 13
puts [apply $twice $plusThree 7]

Tcl uses apply command to apply an anonymous function (since 8.6).

XACML

[edit]

The XACML standard defines higher-order functions in the standard to apply a function to multiple values of attribute bags.

rule allowEntry{
    permit
    condition anyOfAny(function[stringEqual], citizenships, allowedCitizenships)
}

The list of higher-order functions in XACML can be found here.

XQuery

[edit]
declare function local:twice($f, $x) {
  $f($f($x))
};

declare function local:plusthree($i) {
  $i + 3
};

local:twice(local:plusthree#1, 7) (: 13 :)

Alternatives

[edit]

Function pointers

[edit]

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:

#include <stdio.h>

double square(double x)
{
    return x * x;
}

double cube(double x)
{
    return x * x * x;
}

/* Compute the integral of f() within the interval [a,b] */
double integral(double f(double x), double a, double b, int n)
{
    int i;
    double sum = 0;
    double dt = (b - a) / n;
    for (i = 0;  i < n;  ++i) {
        sum += f(a + (i + 0.5) * dt);
    }
    return sum * dt;
}

int main()
{
    printf("%g\n", integral(square, 0, 1, 100));
    printf("%g\n", integral(cube, 0, 1, 100));
    return 0;
}

The qsort function from the C standard library uses a function pointer to emulate the behavior of a higher-order function.

Macros

[edit]

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.

Dynamic code evaluation

[edit]

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:

  • The argument code to be executed is usually not statically typed; these languages generally rely on dynamic typing to determine the well-formedness and safety of the code to be executed.
  • The argument is usually provided as a string, the value of which may not be known until run-time. This string must either be compiled during program execution (using just-in-time compilation) or evaluated by interpretation, causing some added overhead at run-time, and usually generating less efficient code.

Objects

[edit]

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:

program example;

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 10
end.

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

[edit]

Defunctionalization can be used to implement higher-order functions in languages that lack first-class functions:

// Defunctionalized function data structures
template<typename T> struct Add { T value; };
template<typename T> struct DivBy { T value; };
template<typename F, typename G> struct Composition { F f; G g; };

// Defunctionalized function application implementations
template<typename F, typename G, typename X>
auto apply(Composition<F, G> f, X arg) {
    return apply(f.f, apply(f.g, arg));
}

template<typename T, typename X>
auto apply(Add<T> f, X arg) {
    return arg  + f.value;
}

template<typename T, typename X>
auto apply(DivBy<T> f, X arg) {
    return arg / f.value;
}

// Higher-order compose function
template<typename F, typename G>
Composition<F, G> compose(F f, G g) {
    return Composition<F, G> {f, g};
}

int main(int argc, const char* argv[]) {
    auto f = compose(DivBy<float>{ 2.0f }, Add<int>{ 5 });
    apply(f, 3); // 4.0f
    apply(f, 9); // 7.0f
    return 0;
}

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.

See also

[edit]

References

[edit]
Revisions and contributorsEdit on WikipediaRead on Wikipedia
from Grokipedia
In , a higher-order function is a function that either takes one or more functions as arguments, returns a function as its result, or both. This is enabled when functions are treated as first-class citizens, allowing them to be passed around and manipulated like any other . The idea of higher-order functions traces its origins to , a for expressing through function and application, developed by in the 1930s. In , functions are values that can accept other functions as inputs or produce them as outputs, forming the theoretical foundation for paradigms. This higher-order nature distinguishes from earlier computational models and underpins modern programming languages that support functional features. Higher-order functions are a of , appearing prominently in languages such as (introduced in 1958), ML, , and even in mainstream languages like and Python through constructs like anonymous functions and callbacks. They promote abstraction and code reuse by allowing programmers to define general-purpose operations that work with arbitrary functions, such as map (which applies a function to each element of a collection), filter (which selects elements based on a predicate function), and fold (which accumulates a result by iteratively applying a function). For example, in a functional language, the map operation might be expressed as map(f, list) to transform every item in list using f. By facilitating composition and modularity, higher-order functions reduce redundancy and enhance expressiveness, making complex algorithms more concise and easier to reason about, though they can introduce challenges in type systems and performance optimization in certain implementations.

Definition and Basic Concepts

Definition

A higher-order function is a function that does at least one of the following: takes one or more functions as arguments, returns a function as a result, or both. This allows functions to be manipulated as data, enabling more abstract and reusable code structures compared to first-order functions, which operate exclusively on non-function values like numbers, strings, or other primitive data types. The term and concept gained prominence in the 1960s within the development of , where described functions as first-class objects that could be passed as parameters or returned from other functions, laying foundational ideas for higher-order usage. Higher-order functions build on this by requiring language support for functions as first-class citizens, allowing them to be assigned to variables, passed around, and composed dynamically. To illustrate, consider a basic example of a higher-order function called map, which applies a given function to each element of a list:

function map(func, list): result = empty list for each item in list: append func(item) to result return result

function map(func, list): result = empty list for each item in list: append func(item) to result return result

Here, map takes a function func as its first argument and transforms the input list by applying func to every element, producing a new list of results.

Relation to First-Class Functions

First-class functions refer to functions in a programming language that are treated as first-class citizens, meaning they can be manipulated in the same way as other values, such as integers or strings. This treatment allows functions to be assigned to variables, passed as arguments to other functions, returned as results from functions, and stored in data structures like lists or arrays. A key aspect of this status is the ability to create functions dynamically at runtime, often through mechanisms like anonymous functions or closures, without requiring compile-time declaration. These properties collectively define the criteria for first-class functions: they must be denotable by variables, passable as arguments, returnable as results, storable in structures, and creatable dynamically. This framework enables languages to support advanced programming paradigms by elevating functions from mere to versatile entities. The relationship to higher-order functions is foundational, as higher-order functions—those that accept functions as inputs or produce them as outputs—depend on first-class treatment to operate on functions as manipulable . Without this capability, functions cannot be abstracted or composed in higher-order ways, limiting expressiveness. For instance, in early Fortran implementations, such as the original and FORTRAN II, functions could not be passed as arguments, restricting the language to usage and preventing higher-order constructs.

Distinction from First-Order Functions

First-order functions are those that operate exclusively on basic data types, such as integers, strings, or other non-function values, without accepting functions as arguments or returning them as results. This restriction limits their scope to direct computations on primitive or structured data, akin to procedures in early imperative languages that manipulate variables without meta-level operations on code. In contrast, higher-order functions extend this paradigm by treating functions as values, enabling them to be passed as inputs, returned as outputs, or stored in data structures, which significantly enhances abstraction power, reusability, and expressiveness. This allows for sophisticated compositions, such as functors that generalize operations over types or monads that encapsulate computational effects, capabilities unattainable with functions alone. While first-class functions—where functions are values like any other—are necessary to support higher-order functions, they are not sufficient without the explicit use of functions operating on other functions. The benefits of higher-order functions include improved code modularity and reduced duplication, as patterns like , filter, and reduce abstract common iterations over data structures, promoting reusable components over repetitive implementations. However, these advantages come with potential drawbacks, such as increased complexity in due to indirect and dynamic control flows that obscure execution traces. Additionally, higher-order functions can introduce performance overhead from function indirection, closures, and repeated invocations, complicating optimization in resource-constrained environments.

Examples

Mathematical Examples

One fundamental example of a higher-order function in mathematics is , which takes two functions f:XYf: X \to Y and g:YZg: Y \to Z and produces a new function h=fg:XZh = f \circ g: X \to Z defined by h(x)=f(g(x))h(x) = f(g(x)) for all xXx \in X. This operation, central to , treats functions themselves as objects upon which another function (composition) acts, thereby mapping pairs of s to a single morphism in a category. In , differentiation and integration provide classic illustrations of higher-order functions, as they operate directly on functions to yield new functions. The differentiation operator DD, given by D(f)=fD(f) = f' where ff' is the of a continuously ff, maps from the of continuously s to the of continuous functions. Similarly, the indefinite integration operator, often denoted dx\int \cdot \, dx, takes an integrable function and returns its , another function. These operators are linear and unbounded on appropriate function s, such as those of smooth or integrable functions over R\mathbb{R}. Fixed-point combinators offer another mathematical example of higher-order functions, enabling the construction of recursive definitions in a non-recursive framework. The , defined such that for any function ff, Yf=f(Yf)Y f = f (Y f), produces a fixed point of ff—a value xx satisfying x=f(x)x = f(x)—without naming the fixed point explicitly. This higher-order construction, originating in , allows to be encoded purely through and is foundational for modeling in function-based systems. In , the exemplifies a higher-order mapping on infinite-dimensional s. For a function fL1(R)f \in L^1(\mathbb{R}) or L2(R)L^2(\mathbb{R}), the f^:RC\hat{f}: \mathbb{R} \to \mathbb{C} is defined by f^(ξ)=f(x)e2πixξdx,\hat{f}(\xi) = \int_{-\infty}^{\infty} f(x) e^{-2\pi i x \xi} \, dx, transforming ff into its frequency representation f^\hat{f}, which resides in a dual . This operator, unitary on L2(R)L^2(\mathbb{R}) by the , decomposes functions into superpositions of exponentials, facilitating analysis of signals and partial differential equations.

Programming Examples

Higher-order functions in programming enable the of common algorithmic patterns by treating functions as that can be passed as arguments or returned as results. These patterns, inspired by mathematical where one function is applied to the output of another, allow for more modular and reusable code. A canonical example is the function, which applies a given function to each element of a , producing a new of the same length with the transformed values. For instance, applying a square function to the [1, 2, 3] yields [1, 4, 9]. In , this can be expressed recursively as:

function map(transform, sequence): if sequence is empty: return empty list else: return cons(transform(first(sequence)), map(transform, rest(sequence)))

function map(transform, sequence): if sequence is empty: return empty list else: return cons(transform(first(sequence)), map(transform, rest(sequence)))

This construction demonstrates how map acts as a higher-order function by accepting the transformer as an argument. Another fundamental pattern is the filter function, which selects elements from a sequence based on a predicate function that returns true or false for each element, preserving the original order. For example, filtering even numbers from [1, 2, 3] results in . Pseudocode for filter might look like:

function filter(predicate, sequence): if sequence is empty: return empty list else if predicate(first(sequence)): return cons(first(sequence), filter(predicate, rest(sequence))) else: return filter(predicate, rest(sequence))

function filter(predicate, sequence): if sequence is empty: return empty list else if predicate(first(sequence)): return cons(first(sequence), filter(predicate, rest(sequence))) else: return filter(predicate, rest(sequence))

Here, filter is higher-order because it takes the predicate as input to define the selection criterion dynamically. The reduce (or ) function accumulates a single value from a by repeatedly applying a binary operator function, starting from an initial value. For summing [1, 2, 3] with an initial value of 0 using an add operator, the result is 6. A left-fold implementation is:

function reduce(operator, initial, sequence): if sequence is empty: return initial else: return reduce(operator, operator(initial, first(sequence)), rest(sequence))

function reduce(operator, initial, sequence): if sequence is empty: return initial else: return reduce(operator, operator(initial, first(sequence)), rest(sequence))

This higher-order usage allows the accumulation logic to be parameterized by the operator, facilitating operations like , product, or . Function factories provide another illustration, where a higher-order function returns a new function specialized for a particular context, often using closures to capture variables. For example, a multiplier factory taking n returns a function that multiplies its input by n, such as multiplier(3) applied to 4 yielding 12. In :

function multiplier(n): return function(x): return x * n

function multiplier(n): return function(x): return x * n

This pattern enables the creation of customized functions without hardcoding parameters, enhancing code flexibility.

JavaScript Array Methods

In JavaScript, array methods such as map(), filter(), and reduce() provide concrete implementations of higher-order functions, allowing developers to manipulate arrays by passing in callback functions. The map() method creates a new array populated with the results of calling a provided callback function on every element in the calling array. It transforms each element without modifying the original array. For example:

javascript

const numbers = [1, 4, 9]; const roots = numbers.map(Math.sqrt); console.log(roots); // [1, 2, 3]

const numbers = [1, 4, 9]; const roots = numbers.map(Math.sqrt); console.log(roots); // [1, 2, 3]

This demonstrates map() applying the Math.sqrt function to each element. The filter() method creates a shallow copy of a portion of the array, filtered down to just the elements that pass the test implemented by the provided callback function. It returns a new array with elements for which the callback returns a truthy value. For example:

javascript

const numbers = [1, 5, 10, 15]; const filtered = numbers.filter(num => num >= 10); console.log(filtered); // [10, 15]

const numbers = [1, 5, 10, 15]; const filtered = numbers.filter(num => num >= 10); console.log(filtered); // [10, 15]

This example filters numbers greater than or equal to 10. The reduce() method executes a reducer callback function on each element of the array, in order, to reduce it to a single value. It applies the callback against an accumulator and each element. For example, to sum an array:

javascript

const array = [1, 2, 3, 4]; const sum = array.reduce((accumulator, currentValue) => accumulator + currentValue, 0); console.log(sum); // 10

const array = [1, 2, 3, 4]; const sum = array.reduce((accumulator, currentValue) => accumulator + currentValue, 0); console.log(sum); // 10

Here, the callback adds each element to the accumulator, starting from an initial value of 0.

Theoretical Foundations

Lambda Calculus

provides the foundational theoretical model for higher-order functions, originating as an untyped developed by in the early 1930s to explore the foundations of logic and computation. The untyped consists of three primary syntactic elements: variables, which serve as placeholders; abstractions, denoted as λx.M\lambda x.M, where xx is a variable bound in the term MM; and applications, written as MNM N, representing the application of term MM (function) to term NN (argument). These constructs allow functions to be treated as first-class entities that can be passed as arguments or returned as results, enabling higher-order functionality without any type restrictions. A key illustration of higher-order functions in is the encoding of natural numbers via Church numerals, which represent numbers purely as functional abstractions. For instance, the numeral for 0 is λf.λx.x\lambda f.\lambda x.x, which applies no functions; 1 is λf.λx.fx\lambda f.\lambda x.f x, applying ff once; and 2 is λf.λx.f(fx)\lambda f.\lambda x.f (f x), applying ff twice to xx. These encodings demonstrate how higher-order functions—here, the numeral takes a function ff and applies it iteratively—can model basic data structures and operations, such as successor or , entirely within the calculus. The primary mechanism for computation in lambda calculus is beta-reduction, the rule that evaluates function applications by substituting arguments into abstractions: (λx.M)NM[N/x](\lambda x.M) N \to M[N/x], where M[N/x]M[N/x] denotes MM with all free occurrences of xx replaced by NN, avoiding variable capture. This reduction step captures the essence of higher-order function application, allowing terms to simplify through successive substitutions, potentially leading to if no further redexes (reducible expressions) remain. Lambda calculus achieves through its expressive power, as higher-order functions enable the encoding of arbitrary recursive computations equivalent to those of a . This equivalence was established by showing that any λ\lambda-definable function corresponds to a , and vice versa, via encodings like Church numerals for data and fixed-point combinators for , thus proving that the untyped system can simulate universal computation.

Category Theory

In category theory, higher-order functions manifest as structural mappings that operate on entire categories or their components, providing an abstract framework for composition and abstraction beyond individual morphisms. Functors serve as a primary example, defined as mappings F:CDF: \mathcal{C} \to \mathcal{D} between categories C\mathcal{C} and D\mathcal{D} that preserve the categorical structure by sending objects to objects and morphisms to morphisms, while respecting composition and identities: F(gf)=F(g)F(f)F(g \circ f) = F(g) \circ F(f) and F(idX)=idF(X)F(\mathrm{id}_X) = \mathrm{id}_{F(X)}. This preservation ensures that functors act as higher-order operations, transforming not just elements but the relational structure of one category into another, analogous to functions that take functions as inputs in programming paradigms. Natural transformations extend this higher-order perspective by functioning as "arrows between arrows," specifically as morphisms between functors. Given functors F,G:CDF, G: \mathcal{C} \to \mathcal{D}, a natural transformation η:FG\eta: F \Rightarrow G consists of a family of morphisms ηX:F(X)G(X)\eta_X: F(X) \to G(X) for each object XX in C\mathcal{C}, satisfying the naturality condition that for any morphism f:XYf: X \to Y in C\mathcal{C}, the diagram F(X)ηXG(X)F(f)G(f)F(Y)ηYG(Y)\begin{CD} F(X) @>{\eta_X}>> G(X) \\ @V{F(f)}VV @VV{G(f)}V \\ F(Y) @>>{\eta_Y}> G(Y) \end{CD}
Add your contribution
Related Hubs
Contribute something
User Avatar
No comments yet.