Conceptintro
Higher-order function
Also called higher-order procedure.
A higher-order function takes a function as an argument or returns a function as its result. Map, filter, fold, sort with a key, composition and callbacks are the common forms.
- Applies to
- core-languages
Idea
A higher-order function is a function that takes a function as an argument, returns a function as its result, or does both.1 A language can have higher-order functions only when functions are values. Code must be able to pass a function, return it and store it in a variable, as it does with a number. Strachey called such values first class. He called the procedures of ALGOL second class, because no ALGOL expression can have a procedure as its result.2
Higher-order functions separate the shape of a computation from its details. A loop that changes each element of a list has the same shape for every change. A higher-order function holds the loop once and takes the change as an argument. In Python, apply_to_all below takes a function, and make_adder returns one.
def apply_to_all(f, items):
result = []
for item in items:
result.append(f(item))
return result
def make_adder(n):
return lambda x: x + n
print(apply_to_all(abs, [-2, 3, -5]))
add_ten = make_adder(10)
print(apply_to_all(add_ten, [1, 2, 3]))
print(apply_to_all(str.upper, ["a", "b"]))
[2, 3, 5]
[11, 12, 13]
['A', 'B']
The built-in function abs, the method str.upper and the result of make_adder are all function objects, so apply_to_all accepts each of them. The function that make_adder returns uses n after make_adder has returned. Closure explains how it keeps n.
How it works
Functions as values
In Python, a def statement or a lambda expression makes a function object when it runs.3 The name of the function is a variable like any other, and its value is the object. In C, a function name in an expression converts to a pointer to the function, except as the operand of sizeof, _Alignof or &.4 The call operator takes an expression of pointer-to-function type, so f(x) and (*f)(x) mean the same thing.5
The machine view
At the machine level, a function value has one of two forms:
- A code pointer. A function that uses no outer variables needs only the address of its code. A C function pointer and a Rust
fntype are code pointers.6 - A code pointer and an environment. A function that uses outer variables also needs those values. The value is a pair: the address of the code and a record of the captured values.
A call of a named function is a direct call: the address of the target is fixed in the instruction. A call through a function value is an indirect call. The program loads the address from the value and then jumps to it. The Rust program below shows the sizes of the forms on a 64-bit target.
use std::mem::size_of_val;
fn add_one(x: i32) -> i32 {
x + 1
}
fn main() {
let k = 10;
let pointer: fn(i32) -> i32 = add_one;
let closure = move |x: i32| x + k;
let erased: &dyn Fn(i32) -> i32 = &closure;
let boxed: Box<dyn Fn(i32) -> i32> = Box::new(closure);
println!("fn pointer: {} bytes", size_of_val(&pointer));
println!("closure: {} bytes", size_of_val(&closure));
println!("&dyn Fn: {} bytes", size_of_val(&erased));
println!("Box<dyn Fn>: {} bytes", size_of_val(&boxed));
println!("{} {} {} {}", pointer(1), closure(1), erased(1), boxed(1));
}
fn pointer: 8 bytes
closure: 4 bytes
&dyn Fn: 16 bytes
Box<dyn Fn>: 16 bytes
2 11 11 11
The function pointer is one address. The closure holds only the captured k, because its type tells the compiler where its code is. The dyn forms erase the type, so they hold two pointers: one to the captured data and one to a vtable. The vtable is a table of function pointers for the methods of the trait.7
Other languages use the same two forms behind an object. A C++ lambda expression makes an object of a unique class with a call operator. A lambda that captures nothing also converts to a plain function pointer.8 A Java lambda or method reference makes an object of a functional interface, an interface with one abstract method. The call is a call of that method.910 A C# lambda converts to a delegate type such as Func<int, int>. A delegate is a type that represents references to methods with a given parameter list and return type.111213
The common operations
Most standard libraries supply the same small set of higher-order functions for collections:
| Operation | What it does | Python | JavaScript | C# | Rust |
|---|---|---|---|---|---|
| map | applies f to each element and keeps the results |
map |
map |
Select |
Iterator::map |
| filter | keeps the elements for which p returns true |
filter |
filter |
Where |
Iterator::filter |
| fold | combines the elements with f and a start value |
functools.reduce |
reduce |
Aggregate |
Iterator::fold |
| sort | orders the elements by a key or a comparator | sorted(key=...) |
sort(compare) |
OrderBy |
sort_by_key |
In Python, map and filter return iterators, and reduce applies a function of two arguments cumulatively from the left.1415 In JavaScript, map and filter make a fresh array, and reduce passes the accumulator and the element to the callback.161718 The example files show the same operations in each language.
A sort takes a function in one of two shapes. A key function takes one element and returns a value that the sort compares, as in Python sorted(words, key=len).14 A comparator takes two elements and returns a negative number, zero or a positive number. The C function qsort and the Go function slices.SortFunc take comparators.1920 A key function is often shorter. A comparator can express any order, but it must follow the contract of the sort (see Pitfalls).
C++ names the map operation std::transform and the fold std::accumulate. The ranges forms of the algorithms also take a projection, a function that the algorithm applies to each element before it compares or uses it.21
Eager and lazy results
A higher-order function can do its work at once or when the consumer asks for the results. JavaScript Array.prototype.map is eager: it calls the callback for each element and returns a complete array.16 Python map and filter, the Rust iterator adapters and C# Select and Where are lazy. They return an object that calls the function only when code asks for the next item.142223 A lazy pipeline of several steps makes no intermediate collections. It also means that the function runs later, and perhaps more than once or not at all. Iterator covers the protocol that lazy results use.
Composition and returned functions
A function that returns a function can build behaviour from parts. The function compose(f, g) returns a function that applies g and then f. In Java, the interface Function has the default methods andThen and compose for this.24 A returned function usually needs the arguments of the call that made it, so it is a closure. Closure describes how the captured variables stay alive.
Callbacks
A callback is a function that one part of a program gives to another, so that the other part can call it later. An event handler, a completion function and a comparator are callbacks. The caller gives control of the timing to the receiver. The C# guide says that the ability to refer to a method as a parameter makes delegates ideal for callback methods.11
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | |
| SQL | Does not apply | A query has no function values. |
| Bash | Idiom | Functions are not values, but a command name can come from a variable, so a function name in a variable acts as a function argument. Alternative: Pass the name of a function and call it as "$f" args. |
| PowerShell | Native | |
| HTML | Does not apply | Markup has no functions. |
| CSS | Does not apply | Style rules have no function values. |
| Regular expressions | Does not apply | A pattern has no functions. |
| Language | Verdict | Form |
|---|---|---|
| Python | native | function objects from def and lambda; map, filter, functools.reduce, key= |
| JavaScript | native | function objects; map, filter, reduce, sort on arrays |
| TypeScript | native | as JavaScript, with function types such as (x: T) => U |
| Java | native | lambda expressions and method references that implement a functional interface |
| C | native, limited | function pointers; no lambda expressions and no captured state |
| C++ | native | lambda expressions, function objects, function templates and std::function |
| C# | native | delegates such as Func<T, TResult>; LINQ methods |
| Go | native | function types such as func(T) U; function literals |
| Rust | native | closures with the traits Fn, FnMut and FnOnce; fn pointers |
| Kotlin | native | function types such as (Int) -> Int; lambdas; inline functions |
| PowerShell | native | script blocks; &; ForEach-Object, Where-Object, Sort-Object |
| Bash | idiom | the name of a function in a variable |
| SQL | n/a | a query has no function values |
| Regex | n/a | a pattern has no functions |
| HTML | n/a | markup has no functions |
| CSS | n/a | style rules have no function values |
Each language with a native form also has its own type for function values. A Go function type denotes all functions with the same parameter and result types, and its zero value is nil.25 Go function values cannot be compared, except with nil.26 Rust gives each closure a unique type, and a generic parameter names it through the traits Fn, FnMut and FnOnce.27 A TypeScript function type expression has the form (a: string) => void.28 A Kotlin function type has the form (Int) -> Int, and ((Int) -> Int)? is its nullable form.29
A PowerShell script block is a collection of statements that can be used as a single unit. A variable can hold a script block. The call operator & runs it.30 ForEach-Object runs a script block for each input object and sets $_ to the current object.31
Bash functions are not values, but a command name can come from an expansion. When the first word of a command has no slash and names a shell function, the shell calls that function.32 So a variable that holds the name of a function acts as a function argument.
shout() { echo "$1!"; }
whisper() { echo "($1)"; }
apply_to_all() {
local f=$1
shift
for item in "$@"; do
"$f" "$item"
done
}
apply_to_all shout pear fig
apply_to_all whisper banana
pear!
fig!
(banana)
The name is a string, so the shell finds out whether the function exists only at the call.
from functools import reduce
def twice(f, x):
return f(f(x))
def compose(f, g):
return lambda x: f(g(x))
words = ["pear", "fig", "banana"]
print(twice(lambda n: n * 3, 2))
print(list(map(len, words)))
print(list(filter(lambda w: len(w) > 3, words)))
print(reduce(lambda total, n: total + n, [1, 2, 3, 4], 0))
print(sorted(words, key=len))
add_then_double = compose(lambda n: n * 2, lambda n: n + 1)
print(add_then_double(5))
18
[4, 3, 6]
['pear', 'banana']
10
['fig', 'pear', 'banana']
12
- Verdict: native. A function is an object.
defandlambdaboth make one, and a function can take, store and return such objects. mapandfilterreturn iterators, not lists. The work happens when a consumer such aslistasks for the items, and an iterator gives its items only once (see Pitfalls).reduceis in thefunctoolsmodule, not in the built-in names.sorted,minandmaxtake akeyfunction of one argument. The sort calls it once for each item and compares the results.
#include <algorithm>
#include <functional>
#include <numeric>
#include <print>
#include <string>
#include <vector>
template <typename F>
int twice(F f, int x) {
return f(f(x));
}
auto compose(auto f, auto g) {
return [=](auto x) { return f(g(x)); };
}
int main() {
std::vector<std::string> words{"pear", "fig", "banana"};
std::println("{}", twice([](int n) { return n * 3; }, 2));
std::vector<std::size_t> lengths(words.size());
std::ranges::transform(words, lengths.begin(), &std::string::size);
std::println("{}", lengths);
std::vector<int> numbers{1, 2, 3, 4};
std::println("{}", std::accumulate(numbers.begin(), numbers.end(), 0, std::plus<>{}));
std::ranges::sort(words, {}, [](const std::string& w) { return w.size(); });
std::println("{}", words);
std::function<int(int)> step = compose([](int n) { return n * 2; }, [](int n) { return n + 1; });
std::println("{}", step(5));
}
18
[4, 3, 6]
10
["fig", "pear", "banana"]
12
- Verdict: native. A lambda expression makes a closure object of an unnamed class with a call operator. A function template such as
twiceaccepts any callable type. - The compiler makes a copy of the template for each callable type, so it knows the called function and can inline it.
std::function<int(int)>holds any callable with that signature behind one type. A call of an emptystd::functionthrowsstd::bad_function_call(see Pitfalls).- The ranges algorithms take a projection, here the third argument of
sort, which plays the role of a key function.
import java.util.Comparator;
import java.util.List;
import java.util.function.BinaryOperator;
import java.util.function.Function;
public class Main {
static <T> T twice(Function<T, T> f, T x) {
return f.apply(f.apply(x));
}
public static void main(String[] args) {
List<String> words = List.of("pear", "fig", "banana");
System.out.println(twice(n -> n * 3, 2));
System.out.println(words.stream().map(String::length).toList());
System.out.println(words.stream().filter(w -> w.length() > 3).toList());
BinaryOperator<Integer> add = Integer::sum;
System.out.println(List.of(1, 2, 3, 4).stream().reduce(0, add));
System.out.println(words.stream().sorted(Comparator.comparing(String::length)).toList());
Function<Integer, Integer> addOne = n -> n + 1;
Function<Integer, Integer> addThenDouble = addOne.andThen(n -> n * 2);
System.out.println(addThenDouble.apply(5));
}
}
18
[4, 3, 6]
[pear, banana]
10
[fig, pear, banana]
12
- Verdict: native. A lambda expression or a method reference such as
String::lengthmakes an object of a functional interface: an interface with one abstract method. - The package
java.util.functionhas the common shapes:Function,Predicate,Supplier,ConsumerandBinaryOperator. A call goes through the method of the interface, hereapply. Functionhas the default methodsandThenandcompose, which return a composed function.- The type parameters of these interfaces take reference types, so
Function<Integer, Integer>boxes eachint. Primitive shapes such asIntUnaryOperatoravoid the boxing.
#include <stdio.h>
#include <stdlib.h>
static int triple(int n) { return n * 3; }
static int square(int n) { return n * n; }
static int twice(int (*f)(int), int x) { return f(f(x)); }
static void map_ints(int *items, size_t n, int (*f)(int)) {
for (size_t i = 0; i < n; i++) {
items[i] = f(items[i]);
}
}
static int compare_ints(const void *a, const void *b) {
int x = *(const int *)a;
int y = *(const int *)b;
return (x > y) - (x < y);
}
int main(void) {
printf("%d\n", twice(triple, 2));
int items[] = {5, -2, 9, 1};
size_t n = sizeof items / sizeof items[0];
map_ints(items, n, square);
qsort(items, n, sizeof items[0], compare_ints);
for (size_t i = 0; i < n; i++) {
printf("%d ", items[i]);
}
printf("\n");
return 0;
}
18
1 4 25 81
- Verdict: native, in a limited form. A pointer to a function can be a parameter, a variable or a return value. A function name in an expression converts to such a pointer.
- C has no lambda expressions and no closures. A callback that needs state takes an extra
void *argument that points to the state. qsortcalls the comparison function through the pointer for each comparison. The comparator returns a negative, zero or positiveint(see Pitfalls).
int Twice(Func<int, int> f, int x) => f(f(x));
Func<A, C> Compose<A, B, C>(Func<B, C> f, Func<A, B> g) => x => f(g(x));
string[] words = ["pear", "fig", "banana"];
Console.WriteLine(Twice(n => n * 3, 2));
Console.WriteLine(string.Join(", ", words.Select(w => w.Length)));
Console.WriteLine(string.Join(", ", words.Where(w => w.Length > 3)));
Console.WriteLine(new[] { 1, 2, 3, 4 }.Aggregate(0, (total, n) => total + n));
Console.WriteLine(string.Join(", ", words.OrderBy(w => w.Length)));
var addThenDouble = Compose<int, int, int>(n => n * 2, n => n + 1);
Console.WriteLine(addThenDouble(5));
18
4, 3, 6
pear, banana
10
fig, pear, banana
12
- Verdict: native. A delegate is a type for methods with a given signature. The generic delegates
Func<T, TResult>andAction<T>cover the common shapes. - A lambda expression or a method group converts to a delegate type. A call through the delegate calls the method.
- LINQ names the common operations
Select(map),Where(filter),Aggregate(fold) andOrderBy(sort by key). SelectandWhereuse deferred execution. The query runs when code enumerates the result, here insidestring.Join.
const twice = (f, x) => f(f(x));
const compose = (f, g) => (x) => f(g(x));
const words = ["pear", "fig", "banana"];
console.log(twice((n) => n * 3, 2));
console.log(words.map((w) => w.length));
console.log(words.filter((w) => w.length > 3));
console.log([1, 2, 3, 4].reduce((total, n) => total + n, 0));
console.log([...words].sort((a, b) => a.length - b.length));
console.log([10, 9, 1].sort());
console.log([10, 9, 1].sort((a, b) => a - b));
const addThenDouble = compose((n) => n * 2, (n) => n + 1);
console.log(addThenDouble(5));
18
[ 4, 3, 6 ]
[ 'pear', 'banana' ]
10
[ 'fig', 'pear', 'banana' ]
[ 1, 10, 9 ]
[ 1, 9, 10 ]
12
- Verdict: native. Functions are objects. Function declarations, function expressions and arrow functions all make values that code can pass and return.
map,filter,forEachandsomecall the callback with three arguments: the element, its index and the array.reduceadds the accumulator in front, for four arguments. A function that has an optional second parameter can get the index by mistake (see Pitfalls).sortwithout a comparator converts the elements to strings and compares the strings, so[10, 9, 1]sorts as1, 10, 9. A comparator returns a negative number, zero or a positive number.sortchanges the array in place. The spread copy[...words]keeps the original order ofwords.
type Transform<T, U> = (value: T) => U;
function mapAll<T, U>(items: T[], f: Transform<T, U>): U[] {
const result: U[] = [];
for (const item of items) {
result.push(f(item));
}
return result;
}
function compose<A, B, C>(f: Transform<B, C>, g: Transform<A, B>): Transform<A, C> {
return (x) => f(g(x));
}
const words: string[] = ["pear", "fig", "banana"];
const lengths: number[] = mapAll(words, (w) => w.length);
console.log(lengths);
const describe = compose((n: number) => `${n} letters`, (w: string) => w.length);
console.log(mapAll(words, describe));
words.forEach((w) => console.log(w.toUpperCase()));
[ 4, 3, 6 ]
[ '4 letters', '3 letters', '6 letters' ]
PEAR
FIG
BANANA
- Verdict: native. TypeScript has the functions of JavaScript and adds function types such as
(value: T) => U. - Generic type parameters let one higher-order function work for any element type. The compiler infers
TandUfrom the arguments, and it infers the type of the parameterwfrom the context. - A function with fewer parameters can take the place of a function type with more parameters. So
forEachaccepts a callback with one parameter, althoughforEachpasses three arguments. - The checker removes the types before the program runs, so the types give no checks at run time.
package main
import (
"cmp"
"fmt"
"slices"
)
func Map[T, U any](items []T, f func(T) U) []U {
result := make([]U, 0, len(items))
for _, item := range items {
result = append(result, f(item))
}
return result
}
func compose[A, B, C any](f func(B) C, g func(A) B) func(A) C {
return func(x A) C { return f(g(x)) }
}
func main() {
words := []string{"pear", "fig", "banana"}
lengths := Map(words, func(w string) int { return len(w) })
fmt.Println(lengths)
sorted := slices.Clone(words)
slices.SortFunc(sorted, func(a, b string) int { return cmp.Compare(len(a), len(b)) })
fmt.Println(sorted)
addThenDouble := compose(func(n int) int { return n * 2 }, func(n int) int { return n + 1 })
fmt.Println(addThenDouble(5))
}
[4 3 6]
[fig pear banana]
12
- Verdict: native. A function type such as
func(T) Uis a type like any other. Function literals, named functions and method values all have function types. - The standard library has no
MaporFilterfor slices. A generic function such asMapabove is the usual form. The packageslicestakes functions inSortFunc,IndexFunc,ContainsFuncand others. - The zero value of a function type is
nil. A call of a nil function panics (see Pitfalls). - Function values are not comparable, except with
nil.
fn twice(f: impl Fn(i32) -> i32, x: i32) -> i32 {
f(f(x))
}
fn compose<A, B, C>(f: impl Fn(B) -> C, g: impl Fn(A) -> B) -> impl Fn(A) -> C {
move |x| f(g(x))
}
fn apply_all(fs: &[fn(i32) -> i32], x: i32) -> Vec<i32> {
fs.iter().map(|f| f(x)).collect()
}
fn main() {
let words = vec!["pear", "fig", "banana"];
println!("{}", twice(|n| n * 3, 2));
let lengths: Vec<usize> = words.iter().map(|w| w.len()).collect();
println!("{lengths:?}");
let long: Vec<&&str> = words.iter().filter(|w| w.len() > 3).collect();
println!("{long:?}");
println!("{}", [1, 2, 3, 4].iter().fold(0, |total, n| total + n));
let mut sorted = words.clone();
sorted.sort_by_key(|w| w.len());
println!("{sorted:?}");
let add_then_double = compose(|n: i32| n * 2, |n: i32| n + 1);
println!("{}", add_then_double(5));
println!("{:?}", apply_all(&[|n| n + 1, |n| n * n], 4));
}
18
[4, 3, 6]
["pear", "banana"]
10
["fig", "pear", "banana"]
12
[5, 16]
- Verdict: native. Closures implement the traits
Fn,FnMutorFnOnce. A generic parameter such asimpl Fn(i32) -> i32accepts any closure with that signature. - Each closure has its own type, so the compiler makes a separate copy of
twicefor each closure type. It can then inline the call. - The type
fn(i32) -> i32is a function pointer. Named functions and closures that capture nothing convert to it, as inapply_all. - Iterator adapters such as
mapandfilterare lazy.collectorfoldruns them.
fun twice(f: (Int) -> Int, x: Int): Int = f(f(x))
fun <A, B, C> compose(f: (B) -> C, g: (A) -> B): (A) -> C = { x -> f(g(x)) }
fun main() {
val words = listOf("pear", "fig", "banana")
println(twice({ n -> n * 3 }, 2))
println(words.map(String::length))
println(words.filter { it.length > 3 })
println(listOf(1, 2, 3, 4).fold(0) { total, n -> total + n })
println(words.sortedBy { it.length })
val addThenDouble = compose<Int, Int, Int>({ it * 2 }, { it + 1 })
println(addThenDouble(5))
}
18
[4, 3, 6]
[pear, banana]
10
[fig, pear, banana]
12
- Verdict: native. A function type such as
(Int) -> Intis a type. Lambda expressions, anonymous functions and callable references such asString::lengthare values of function types. - When the last parameter is a function, the lambda can go outside the parentheses, as in
filter { ... }. A lambda with one parameter can call itit. - The collection functions
map,filterandfoldareinline, so the compiler copies the lambda into the call site and makes no function object. - On the JVM, a function value that is not inlined is an object, and a call of it is a virtual call.
function Invoke-Twice {
param([scriptblock]$Action, $Value)
& $Action (& $Action $Value)
}
function New-Composed {
param([scriptblock]$F, [scriptblock]$G)
{ param($x) & $F (& $G $x) }.GetNewClosure()
}
$words = 'pear', 'fig', 'banana'
Invoke-Twice { param($n) $n * 3 } 2
($words | ForEach-Object { $_.Length }) -join ', '
($words | Where-Object { $_.Length -gt 3 }) -join ', '
($words | Sort-Object { $_.Length }) -join ', '
$addThenDouble = New-Composed { param($n) $n * 2 } { param($n) $n + 1 }
& $addThenDouble 5
18
4, 3, 6
pear, banana
fig, pear, banana
12
- Verdict: native. A script block is a value of type
ScriptBlock. A function can take it as a parameter, store it and return it. - The call operator
&runs a script block with arguments.ForEach-Object,Where-ObjectandSort-Objecttake a script block and see the current item as$_. - A returned script block does not keep the variables of the function that made it.
GetNewClosure()copies them, so the composed block can see$Fand$G(see Closure).
Variations and related ideas
- Currying. A function of two arguments can be a function of one argument that returns a function of the other. Frege observed that functions of one argument are enough in the study of functions, for this reason. The transformation is called currying.33
- Partial application. A function that fixes some arguments of another function returns a function of the rest. JavaScript
Function.prototype.bindfixes thethisvalue and leading arguments.34 - Combinators and point-free style. Backus wrote programs as combinations of functions with no variables. His inner product program composes the functional forms Insert, ApplyToAll and Composition.35
- Generic higher-order functions. A function such as
mapworks for any element type only when the language can express it with type parameters. Generics covers this. - Function types and subtypes. A function that accepts more kinds of arguments can stand in for a function that accepts fewer. The TypeScript checker allows a callback with fewer parameters than the function type.28 Subtyping gives the general rule.
- Recursion. A fold replaces an explicit recursive walk of a list. Recursion shows the recursive form.
- Immutability.
mapandfilterreturn fresh collections and leave the input alone, while JavaScriptsortchanges the array in place. Immutability discusses the difference.
Pitfalls
A callback receives more arguments than it expects
JavaScript map calls the callback with three arguments: the element, the index and the array.16 parseInt takes a string and an optional radix, so the index becomes the radix.
This code runs but gives a wrong answer on purpose.
console.log(["1", "2", "3"].map(parseInt));
[ 1, NaN, NaN ]
For the first element, the radix is 0, and parseInt uses base 10. For the second, the radix is 1, and a radix less than 2 gives NaN. For the third, the radix is 2, and "3" is not a digit in base 2.36 The fix is a callback that passes only the element.
console.log(["1", "2", "3"].map((s) => parseInt(s, 10)));
console.log(["1", "2", "3"].map(Number));
[ 1, 2, 3 ]
[ 1, 2, 3 ]
A lazy result is used twice
Python map returns an iterator, and an iterator gives its items only once. A second pass sees an exhausted iterator, which looks like an empty container.37
This code runs but gives a wrong answer on purpose.
lengths = map(len, ["pear", "fig", "banana"])
print(max(lengths))
print(sum(lengths))
6
0
max takes all the items, so sum gets none and returns 0. The fix is lengths = list(map(len, words)), which stores the results once. C# queries have the opposite trap: each enumeration runs the query again, and so calls the function again.23
A method loses its object
In JavaScript, a method that a program passes as a callback is a plain function. The receiver calls it with no object, so this is undefined in strict code.38 All code inside a class is strict code.39
This code raises TypeError, on purpose.
class Counter {
constructor() {
this.count = 0;
}
add(n) {
this.count += n;
}
}
const counter = new Counter();
[1, 2, 3].forEach(counter.add);
console.log(counter.count);
The run stops with TypeError: Cannot read properties of undefined (reading 'count'). The fix is an arrow function, (n) => counter.add(n), or a bound method, counter.add.bind(counter).34
A Java lambda cannot throw a checked exception
The method apply of java.util.function.Function declares no checked exceptions. A lambda body that can throw a checked exception that the function type does not declare is a compile-time error.40
This code does not compile, on purpose.
import java.io.IOException;
import java.util.List;
public class Main {
static String load(String name) throws IOException {
if (name.isEmpty()) {
throw new IOException("empty name");
}
return name.toUpperCase();
}
public static void main(String[] args) {
List<String> names = List.of("a", "b");
System.out.println(names.stream().map(n -> load(n)).toList());
}
}
javac stops with unreported exception IOException; must be caught or declared to be thrown. One fix is a try block inside the lambda that wraps the exception in an unchecked one. Another fix is a separate functional interface whose method declares throws IOException.
A function value is nil or empty
A function variable can hold no function. In Go, the zero value of a function type is nil, and a call of a nil function value causes a run-time panic.2541
This code panics, on purpose.
package main
import "fmt"
func apply(f func(int) int, x int) int {
return f(x)
}
func main() {
var double func(int) int
fmt.Println(apply(double, 3))
}
The program stops with panic: runtime error: invalid memory address or nil pointer dereference. In C++, a call of an empty std::function throws std::bad_function_call.42
This code raises bad_function_call, on purpose.
#include <functional>
#include <print>
int main() {
std::function<int(int)> double_it;
std::println("{}", double_it(3));
}
With libc++, the program stops with terminating due to uncaught exception of type std::__1::bad_function_call. A function parameter that can be absent needs a check before the call. A type that cannot be empty also prevents the error, for example a Rust closure or a non-nullable Kotlin function type.
A comparator overflows
A common C comparator subtracts the two values. The subtraction can overflow, and signed overflow is undefined behaviour.43 The sort then sees a wrong sign, or the program fails in another way.
This code has a memory error, on purpose, and the sanitizer reports it.
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
static int compare_ints(const void *a, const void *b) {
return *(const int *)a - *(const int *)b;
}
int main(void) {
int items[] = {1, INT_MIN, 3};
qsort(items, 3, sizeof items[0], compare_ints);
printf("%d %d %d\n", items[0], items[1], items[2]);
return 0;
}
UndefinedBehaviorSanitizer reports runtime error: signed integer overflow: 1 - -2147483648 cannot be represented in type 'int'. The fix is return (x > y) - (x < y);, which gives -1, 0 or 1 with no arithmetic on the values, as in the C example. A comparator must also give a consistent order. The results for the same objects must be consistent with one another and define a total order on the array.44
Cost
- Indirect calls. A call through a function pointer or a vtable is an indirect call.
qsortcalls the comparator through a pointer for each comparison.19 The compiler usually cannot inline a call when it does not know the target. - Monomorphization. A generic function that takes the function type as a type parameter gets a separate copy for each closure type. Rust does this for generic code, and the result runs as fast as code written for the concrete types.45 Each C++ lambda has its own class, so a function template such as
std::ranges::sortgets a copy for each lambda.8 - Dynamic dispatch.
dyn Fnin Rust hides the type of the closure. A call looks up the target in the vtable at run time, and this prevents inlining.46 - Function objects. On the JVM, each Kotlin function value is an object, and its call is a virtual call. The
inlinemodifier copies the function and its lambda arguments into the call site, which can remove this overhead.47 - Boxing. The generic Java interfaces take reference types, so
Function<Integer, Integer>boxes eachint. The packagejava.util.functionhas primitive specializations, such asIntUnaryOperatorandToIntFunction, that avoid the boxing.24 - Intermediate collections. Each eager
maporfilterstep in JavaScript makes a complete array.16 A chain of lazy steps makes none, but it keeps the work for the time when the consumer asks for items.
History
- 1893 to 1932. Frege observed that functions of one argument are enough to describe functions of several arguments. In the 1920s, Schönfinkel studied combinators. In 1932, Church introduced the notation
λx[M]for a function.33 - 1960. McCarthy defined
maplist[x; f]andsearch[x; p; f; u]in his paper on Lisp, in a section named "Functions with Functions as Arguments". Hismaplistappliesfto the list and to each of its tails.48 - 1967. Strachey gave lectures that named first class and second class objects. He used the procedures of ALGOL as his example of second class values. The notes appeared as a paper in 2000.2
- 1978. Backus described FP systems, where programs are combinations of functions with no variables. He called the combining operations functional forms.35
- 2008. Python 3.0 changed
mapandfilterto return iterators, and it movedreduceto the modulefunctools.49 - 2014. JDK 8 reached General Availability on 18 March 2014. JDK 8 delivered JEP 126, Lambda Expressions and Virtual Extension Methods, which belongs to JSR 335.5051
References
- Kotlin documentation, Higher-order functions and lambdas, Higher-order functions
- Christopher Strachey, Fundamental Concepts in Programming Languages, Higher-Order and Symbolic Computation 13(1-2), 2000 (lecture notes from August 1967), 3.5.1 First and second class objects
- The Python Language Reference, Data model, Python 3.14, 3.2.8.1 User-defined functions
- ISO/IEC 9899:201x, Programming languages, C (N1570, the C11 draft), 6.3.2.1, paragraph 4 (function designators)
- ISO/IEC 9899:201x, Programming languages, C (N1570, the C11 draft), 6.5.2.2, paragraph 1 (function calls)
- The Rust Reference, Function pointer types, coercion from function items and non-capturing closures
- The Rust Reference, Trait objects, the layout of a pointer to a trait object
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [expr.prim.lambda.closure], paragraphs 1 and 8
- The Java Language Specification, Java SE 25 Edition, 9.8 Functional Interfaces
- The Java Language Specification, Java SE 25 Edition, 15.13 Method Reference Expressions
- C# programming guide, Delegates, Overview of delegates
- C# language reference, Lambda expressions, the conversion of a lambda expression to the Func and Action delegate types
- Microsoft .NET API reference, Func<T,TResult> Delegate, Definition
- The Python Standard Library, Built-in Functions, Python 3.14, map(), filter() and sorted()
- The Python Standard Library, functools, Python 3.14, functools.reduce()
- ECMA-262, ECMAScript 2026 Language Specification, 23.1.3.21 Array.prototype.map
- ECMA-262, ECMAScript 2026 Language Specification, 23.1.3.8 Array.prototype.filter
- ECMA-262, ECMAScript 2026 Language Specification, 23.1.3.24 Array.prototype.reduce
- ISO/IEC 9899:201x, Programming languages, C (N1570, the C11 draft), 7.22.5.2 The qsort function
- Go standard library, package slices, func SortFunc
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [alg.transform]
- The Rust Programming Language, chapter 13.2, Methods That Produce Other Iterators
- Microsoft .NET API reference, Enumerable.Select Method, Remarks (deferred execution)
- Java SE 25 API, package java.util.function, package description: function shapes and primitive specializations
- The Go Programming Language Specification, Function types
- The Go Programming Language Specification, Comparison operators
- The Rust Programming Language, chapter 13.1, Moving Captured Values Out of Closures and the Fn Traits
- TypeScript Handbook, More on Functions, Function Type Expressions; Optional Parameters in Callbacks
- Kotlin documentation, Higher-order functions and lambdas, Function types
- PowerShell documentation, about_Script_Blocks, Long description; Using the call operator
- PowerShell documentation, ForEach-Object, Description, script block syntax
- Bash Reference Manual, 3.7.2 Command Search and Execution
- Jesse Alama and Johannes Korbmacher, The Lambda Calculus, Stanford Encyclopedia of Philosophy (Fall 2025 Edition), 3. Brief history of the lambda calculus
- ECMA-262, ECMAScript 2026 Language Specification, 20.2.3.2 Function.prototype.bind
- John Backus, Can Programming Be Liberated from the von Neumann Style? A Functional Style and Its Algebra of Programs, Communications of the ACM 21(8), 1978, 5.2 A Functional Program for Inner Product; 11.2.4 Functional forms
- ECMA-262, ECMAScript 2026 Language Specification, 19.2.5 parseInt ( string, radix )
- Python Glossary, Python 3.14, iterator
- ECMA-262, ECMAScript 2026 Language Specification, 10.2.1.2 OrdinaryCallBindThis
- ECMA-262, ECMAScript 2026 Language Specification, 11.2.2 Strict Mode Code
- The Java Language Specification, Java SE 25 Edition, 11.2.3 Exception Checking
- The Go Programming Language Specification, Calls
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [func.wrap.func.inv], paragraph 2
- ISO/IEC 9899:201x, Programming languages, C (N1570, the C11 draft), 6.5, paragraph 5 (exceptional conditions)
- ISO/IEC 9899:201x, Programming languages, C (N1570, the C11 draft), 7.22.5, paragraph 4 (consistent results of the comparison function)
- The Rust Programming Language, chapter 10.1, Performance of Code Using Generics
- The Rust Programming Language, chapter 18.2, Trait Objects Perform Dynamic Dispatch
- Kotlin documentation, Inline functions, introduction (runtime penalties of function objects)
- John McCarthy, Recursive Functions of Symbolic Expressions and Their Computation by Machine, Part I, Communications of the ACM 3(4), 1960, 3g Functions with Functions as Arguments (maplist and search)
- What's New In Python 3.0, Views And Iterators Instead Of Lists; Builtins
- JEP 126: Lambda Expressions and Virtual Extension Methods, header (Release 8, JSR 335)
- OpenJDK, JDK 8 project page, General Availability date
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag DB0ZNH Edit this page History Report an error Markdown