Conceptadvanced
Combinator
Also called combinator function, combinator pattern, combinator library, SKI combinators, fixed-point combinator, Y combinator.
A combinator is a function that uses only its arguments, such as identity, const and flip. A combinator library gives simple values and functions that join them into larger values of the same type.
- Applies to
- core-languages
Idea
The word combinator has two meanings in programming. The HaskellWiki gives "two distinct meanings" of the word1.
- The narrow meaning. A combinator is "A function or definition with no free variables."1 It uses only its arguments. Identity, const and flip are examples.
- The wide meaning. The combinator pattern is "a style of organizing libraries centered around the idea of combining things."1 A combinator takes values of a type and joins them into a new value of the same type.
def identity(x):
return x
def const(x):
return lambda _: x
def flip(f):
return lambda a, b: f(b, a)
def both(p, q):
return lambda x: p(x) and q(x)
def sub(a, b):
return a - b
def is_even(x):
return x % 2 == 0
def is_positive(x):
return x > 0
print(identity(5))
print(const(7)(99))
print(flip(sub)(2, 10))
print([x for x in range(-2, 5) if both(is_even, is_positive)(x)])
5
7
8
[2, 4]
identity, const and flip use only their arguments. both takes two predicates and returns a new predicate. The result is a predicate too, so a program can give it to both again.
How it works
- Only the arguments. A combinator in the narrow sense refers to no variable outside itself1. Wikipedia gives the definition: "A combinator is a higher-order function that uses only function application and earlier defined combinators to define a result from its arguments."2
- Functions in, functions out. Many combinators take functions and return a new function.
flipreturns a function that callsfwith its two arguments in the other order. Haskell says that "flip f takes its (first) two arguments in the reverse order of f."3 - One type for the parts and the whole. A combinator library has a type, functions that make simple values of the type, and combinators that join values into more complex values of the same type1. A combinator can take the result of another combinator, so small parts build large ones.
- An example library. "In computer programming, a parser combinator is a higher-order function that accepts several parsers as input and returns a new parser as its output."4
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Standard library | |
| Java | Standard library | |
| C | Absent | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | |
| Go | Native | |
| Rust | Standard library | |
| Kotlin | Native | A Kotlin function can return a lambda with a function type, so identity, const and flip are short generic functions. No example file exists because kotlinc is not installed. |
| SQL | Does not apply | Standard SQL has no function values, so no function can take or return a function. |
| Bash | Idiom | |
| PowerShell | Idiom | A PowerShell function can take script blocks and return a new script block, and the method GetNewClosure keeps the variables. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML is a markup language and has no functions. |
| CSS | Does not apply | CSS has no function values. |
| Regular expressions | Does not apply | A regular expression has no functions. |
- Python. Functions are values, so a function can return a lambda.
functools.partialis a combinator in the library. It returns "a new partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords."5 - JavaScript. Arrow functions make combinators short, as in
const flip = (f) => (a, b) => f(b, a). - TypeScript. The same as JavaScript. Generic types describe combinators such as
flip<A, B, C>(f: (a: A, b: B) => C). - Java.
Function.identity()"Returns a function that always returns its input argument."6Predicate.and"Returns a composed predicate that represents a short-circuiting logical AND of this predicate and another."7Predicate.not"Returns a predicate that is the negation of the supplied predicate."7 - C#. A combinator is a method that takes and returns delegates. A lambda "that has one parameter and returns a value" converts to a
Func<T,TResult>delegate8. - C++. "std::identity is a function object type whose operator() returns its argument unchanged."9
std::not_fn"Creates a forwarding call wrapper that returns the negation of the callable object it holds."10std::bind_frontbinds the first arguments of a callable object11. - Rust.
std::convert::identityis "The identity function."12 Rust calls methods such asOption::mapcombinators: "Option has a built in method called map(), a combinator for the simple mapping of Some -> Some and None -> None."13 - Go. "Function literals are closures"14, so a generic function can return a new function value.
- C. C has function pointers but no closures. "A function is a C language construct that associates a compound statement (the function body) with an identifier (the function name)."15 A C function cannot make a new function at run time, so a helper takes the function pointer and the arguments together.
- Bash. Functions are not values, but a function can get the name of another function as an argument. "When the name of a shell function is used as a simple command name, the shell executes the list of commands associated with that function name."16
from functools import partial
def identity(x):
return x
def const(x):
return lambda _: x
def flip(f):
return lambda a, b: f(b, a)
def both(p, q):
return lambda x: p(x) and q(x)
def sub(a, b):
return a - b
print(identity(5))
print(const(7)(99))
print(flip(sub)(2, 10))
is_even = partial(lambda m, x: x % m == 0, 2)
keep = both(is_even, lambda x: x > 0)
print(*[x for x in range(-2, 5) if keep(x)])
5
7
8
2 4
- Verdict: native. A Python function can return a lambda, so each combinator is a short function.
functools.partialis a combinator in the standard library.
#include <functional>
#include <iostream>
auto constant = [](auto x) { return [x](auto&&...) { return x; }; };
auto flip = [](auto f) { return [f](auto a, auto b) { return f(b, a); }; };
auto both = [](auto p, auto q) {
return [p, q](auto x) { return p(x) && q(x); };
};
int main() {
std::cout << std::identity{}(5) << '\n';
std::cout << constant(7)(99) << '\n';
auto sub = [](int a, int b) { return a - b; };
std::cout << flip(sub)(2, 10) << '\n';
auto is_odd = [](int x) { return x % 2 != 0; };
auto keep = both(std::not_fn(is_odd), [](int x) { return x > 0; });
const char* sep = "";
for (int x = -2; x <= 4; ++x) {
if (keep(x)) {
std::cout << sep << x;
sep = " ";
}
}
std::cout << '\n';
}
5
7
8
2 4
- Verdict: stdlib.
std::identityandstd::not_fnare in the header<functional>. A generic lambda that returns a lambda givesconstant,flipandboth.
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
static <A, B, C> BiFunction<B, A, C> flip(BiFunction<A, B, C> f) {
return (b, a) -> f.apply(a, b);
}
static <A, B> Function<B, A> constant(A x) {
return ignored -> x;
}
public static void main(String[] args) {
Function<Integer, Integer> id = Function.identity();
System.out.println(id.apply(5));
System.out.println(Main.<Integer, Integer>constant(7).apply(99));
BiFunction<Integer, Integer, Integer> sub = (a, b) -> a - b;
System.out.println(flip(sub).apply(2, 10));
Predicate<Integer> isEven = x -> x % 2 == 0;
Predicate<Integer> keep = isEven.and(x -> x > 0);
System.out.println(IntStream.rangeClosed(-2, 4).boxed()
.filter(keep)
.map(String::valueOf)
.collect(Collectors.joining(" ")));
}
}
5
7
8
2 4
- Verdict: stdlib.
Function.identityandPredicate.andare in the library. A generic method that returns a lambda givesflipandconstant.
#include <stdio.h>
typedef int (*binop)(int, int);
typedef int (*pred)(int);
static int identity(int x) { return x; }
static int constant(int x, int ignored) {
(void)ignored;
return x;
}
static int call_flipped(binop f, int a, int b) { return f(b, a); }
static int both(pred p, pred q, int x) { return p(x) && q(x); }
static int sub(int a, int b) { return a - b; }
static int is_even(int x) { return x % 2 == 0; }
static int is_positive(int x) { return x > 0; }
int main(void) {
printf("%d\n", identity(5));
printf("%d\n", constant(7, 99));
printf("%d\n", call_flipped(sub, 2, 10));
const char *sep = "";
for (int x = -2; x <= 4; x++) {
if (both(is_even, is_positive, x)) {
printf("%s%d", sep, x);
sep = " ";
}
}
printf("\n");
return 0;
}
5
7
8
2 4
- Verdict: absent. A C function cannot return a new function that keeps its arguments. Each helper takes the function pointers and the arguments in one call.
using System;
using System.Linq;
class Program
{
static T Identity<T>(T x) => x;
static Func<B, A> Const<A, B>(A x) => _ => x;
static Func<B, A, C> Flip<A, B, C>(Func<A, B, C> f) => (b, a) => f(a, b);
static Func<T, bool> Both<T>(Func<T, bool> p, Func<T, bool> q) => x => p(x) && q(x);
static void Main()
{
Console.WriteLine(Identity(5));
Console.WriteLine(Const<int, int>(7)(99));
Func<int, int, int> sub = (a, b) => a - b;
Console.WriteLine(Flip(sub)(2, 10));
var keep = Both<int>(x => x % 2 == 0, x => x > 0);
Console.WriteLine(string.Join(" ", Enumerable.Range(-2, 7).Where(keep)));
}
}
5
7
8
2 4
- Verdict: native. A generic method takes
Funcdelegates and returns a lambda.
const identity = (x) => x;
const constant = (x) => () => x;
const flip = (f) => (a, b) => f(b, a);
const both = (p, q) => (x) => p(x) && q(x);
const sub = (a, b) => a - b;
console.log(identity(5));
console.log(constant(7)(99));
console.log(flip(sub)(2, 10));
const keep = both((x) => x % 2 === 0, (x) => x > 0);
console.log([-2, -1, 0, 1, 2, 3, 4].filter(keep).join(" "));
5
7
8
2 4
- Verdict: native. An arrow function can return an arrow function, so each combinator is one line.
const identity = <T>(x: T): T => x;
const constant =
<A>(x: A) =>
(_: unknown): A =>
x;
const flip =
<A, B, C>(f: (a: A, b: B) => C) =>
(b: B, a: A): C =>
f(a, b);
const both =
<T>(p: (x: T) => boolean, q: (x: T) => boolean) =>
(x: T): boolean =>
p(x) && q(x);
const sub = (a: number, b: number): number => a - b;
console.log(identity(5));
console.log(constant(7)(99));
console.log(flip(sub)(2, 10));
const keep = both<number>((x) => x % 2 === 0, (x) => x > 0);
console.log([-2, -1, 0, 1, 2, 3, 4].filter(keep).join(" "));
5
7
8
2 4
- Verdict: native. Generic types describe each combinator, so
flip(sub)has the type(b: number, a: number) => number.
package main
import "fmt"
func Identity[T any](x T) T { return x }
func Const[A, B any](x A) func(B) A {
return func(B) A { return x }
}
func Flip[A, B, C any](f func(A, B) C) func(B, A) C {
return func(b B, a A) C { return f(a, b) }
}
func Both[T any](p, q func(T) bool) func(T) bool {
return func(x T) bool { return p(x) && q(x) }
}
func main() {
fmt.Println(Identity(5))
fmt.Println(Const[int, int](7)(99))
sub := func(a, b int) int { return a - b }
fmt.Println(Flip(sub)(2, 10))
keep := Both(func(x int) bool { return x%2 == 0 }, func(x int) bool { return x > 0 })
sep := ""
for x := -2; x <= 4; x++ {
if keep(x) {
fmt.Print(sep, x)
sep = " "
}
}
fmt.Println()
}
5
7
8
2 4
- Verdict: native. A generic function returns a function literal, and the literal keeps the arguments.
use std::convert::identity;
fn constant<A: Copy, B>(x: A) -> impl Fn(B) -> A {
move |_| x
}
fn flip<A, B, C>(f: impl Fn(A, B) -> C) -> impl Fn(B, A) -> C {
move |b, a| f(a, b)
}
fn both<T: Copy>(p: impl Fn(T) -> bool, q: impl Fn(T) -> bool) -> impl Fn(T) -> bool {
move |x| p(x) && q(x)
}
fn main() {
println!("{}", identity(5));
println!("{}", constant::<i32, i32>(7)(99));
let sub = |a: i32, b: i32| a - b;
println!("{}", flip(sub)(2, 10));
let keep = both(|x: i32| x % 2 == 0, |x: i32| x > 0);
let kept: Vec<String> = (-2..=4).filter(|&x| keep(x)).map(|x| x.to_string()).collect();
println!("{}", kept.join(" "));
}
5
7
8
2 4
- Verdict: stdlib.
std::convert::identityis in the library, andOptionandIteratorhave many combinator methods. A function that returnsimpl Fngivesconstant,flipandboth.
identity() { echo "$1"; }
constant() { echo "$1"; }
flip() { "$1" "$3" "$2"; }
both() { "$1" "$3" && "$2" "$3"; }
sub() { echo $(($1 - $2)); }
is_even() { (($1 % 2 == 0)); }
is_positive() { (($1 > 0)); }
identity 5
constant 7 99
flip sub 2 10
kept=()
for x in -2 -1 0 1 2 3 4; do
if both is_even is_positive "$x"; then
kept+=("$x")
fi
done
echo "${kept[*]}"
5
7
8
2 4
- Verdict: idiom. Bash functions are not values. A function gets the names of other functions as arguments and calls them, and it runs them at once with the arguments.
Variations and related ideas
- SKI combinators. Combinatory logic uses a few basic combinators. "The simplest example of a combinator is I, the identity combinator, defined by (I x)=x for all terms x."2 "Another simple combinator is K, which manufactures constant functions"2. "A third combinator is S, which is a generalized version of application"2. The SKI calculus is "an extremely simple Turing complete language."17
- Haskell Prelude. The examples of the HaskellWiki "are id, const, and flip respectively."1 For
id, the Prelude says: "This function might seem useless at first glance, but it can be very useful in a higher order context."3 - Fixed-point combinators. Wikipedia describes "a fixed-point combinator (or fixpoint combinator)"18 as a function that "is a higher-order function (i.e., a function that takes a function as argument) that returns some fixed point (a value that is mapped to itself) of its argument function, if one exists."18 "In programming languages that support anonymous functions, fixed-point combinators allow the definition and use of anonymous recursive functions"18. The best known one is the Y combinator of Curry18. "However, they are rarely used in practical programming."18
- Combinators in libraries. Parser combinators4, the
Optionmethods of Rust13 and thePredicatemethods of Java7 are combinator libraries. - Point-free style. A function written only with combinators and composition does not name its arguments. "Tacit programming, also called point-free style, is a programming paradigm in which function definitions do not identify the arguments"19 on which they operate. See Function composition.
Pitfalls
The Y combinator loops in a strict language
The Y combinator needs lazy evaluation. Wikipedia says: "Languages that use strict evaluation, such as Python, C++, and other strict programming languages, can often express Y; however, any implementation is useless in practice since it loops indefinitely until terminating via a stack overflow."18
This code runs but gives a wrong answer on purpose.
Y = lambda f: (lambda x: f(x(x)))(lambda x: f(x(x)))
fact_step = lambda self: lambda n: 1 if n == 0 else n * self(n - 1)
try:
fact = Y(fact_step)
print(fact(5))
except RecursionError as e:
print(type(e).__name__)
RecursionError
Python computes x(x) before it calls f, and that call computes x(x) again. Use the Z combinator. "The Z combinator will work in strict languages"18. It puts x(x) inside a lambda, so Python computes it only when the function gets an argument:
Z = lambda f: (lambda x: f(lambda v: x(x)(v)))(lambda x: f(lambda v: x(x)(v)))
fact_step = lambda self: lambda n: 1 if n == 0 else n * self(n - 1)
print(Z(fact_step)(5))
120
Too many combinators hide the meaning
A long chain of combinators names no arguments, and a reader must work out what each step gets. "The lack of argument naming gives point-free style a reputation of being needlessly obscure"19. Give names to the parts, or write a small function with named parameters.
Cost
A combinator returns a new function, so each call of the result also calls the functions inside it. A chain of combinators adds one call for each step. Some combinators save work. Predicate.and is short-circuiting: "if this predicate is false, then the other predicate is not evaluated."7
History
Combinatory logic "was introduced by Moses Schönfinkel"2 and Haskell Curry. "It is based on combinators, which were introduced by Schönfinkel in 1920"2. Schönfinkel published nothing more on combinators "after his original 1924 paper."2 "Haskell Curry rediscovered the combinators while working as an instructor at Princeton University in late 1927."2 Later, "David Turner used his combinators to implement the SASL programming language."2
References
- Combinator, HaskellWiki, the whole page
- Combinatory logic, Wikipedia, the introduction; In mathematics; Examples of combinators; Compilation of functional languages
- Prelude, the Haskell package base, Miscellaneous functions, id, const and flip
- Parser combinator, Wikipedia, the introduction; Basic idea
- functools, The Python Standard Library, functools.partial
- Interface Function, Java SE 25 API, identity
- Interface Predicate, Java SE 25 API, and; not
- Lambda expressions and anonymous functions, C# language reference, the introduction
- std::identity, C++ reference, cppreference.com, the description; Notes
- std::not_fn, C++ reference, cppreference.com, the description
- std::bind_front, std::bind_back, C++ reference, cppreference.com, the description
- Function identity, The Rust Standard Library, the description
- Combinators, map, Rust By Example, the whole page
- The Go Programming Language Specification, Function literals
- Functions, C reference, cppreference.com, the introduction
- Shell Functions, Bash Reference Manual, 3.3 Shell Functions
- SKI combinator calculus, Wikipedia, the introduction
- Fixed-point combinator, Wikipedia, the introduction; Example implementations; Strict fixed-point combinator
- Tacit programming, Wikipedia, the introduction
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 BJQVD1 Edit this page History Report an error Markdown