Programming Search⌘K

Conceptcore

Function composition

Also called compose, composition of functions, function chaining, compose operator, andThen.

Function composition joins two functions into one: the output of the first is the input of the second. In mathematics (f ∘ g)(x) = f(g(x)). Haskell, F# and Java have it in the language or library.

Applies to
core-languages

Idea

Function composition makes one function from two functions. The new function gives its argument to the first function and gives that result to the second function. Wikipedia gives the definition: "function composition is an act or mechanism to combine simple functions to build more complex ones."1 In mathematics, "When the composite function f∘g (pronounced "f of g") is evaluated at an input x, the result is (f∘g)(x)=f(g(x))."2

def compose(f, g):
    return lambda x: f(g(x))


def inc(x):
    return x + 1


def square(x):
    return x * x


print(compose(square, inc)(6))
print(compose(inc, square)(6))
Output
49
37

compose(square, inc) adds 1 and then squares: 7 times 7 is 49. This is the example of SICP Exercise 1.42, where ((compose square inc) 6) gives 493. The other order squares and then adds 1, so the result is 37.

How it works

  1. The definition. SICP defines "The composition f after g" as the function that maps x to f(g(x))3. The function on the right runs first: "the function f is applied after applying g to x."2
  2. The types. The result of the first function must be a valid argument of the second function. In the Haskell type (.) :: (b -> c) -> (a -> b) -> a -> c, "only the relation between f, g matters (f must accept what g returns)."1
  3. A new function value. compose returns a function, so the language must let a program return functions. Wikipedia says that such a function "can always be defined but languages with first-class functions make it easier."1 Haskell defines the operator in its Prelude as f . g = \ x -> f (g x)4.
  4. Associativity. "The composition of functions is always associative"2: f ∘ (g ∘ h) = (f ∘ g) ∘ h2. So a chain of functions needs no parentheses. The identity function does nothing in a chain. Java Function.identity "Returns a function that always returns its input argument."5

In languages

LanguageVerdictNote
PythonIdiom
C++Idiom
JavaStandard library
CAbsent
C#Idiom
JavaScriptIdiom
TypeScriptIdiom
GoIdiom
RustIdiom
KotlinIdiomThe Kotlin standard library has no compose function, but a function can take two function values and return a lambda that calls both. No example file exists because kotlinc is not installed.
SQLDoes not applyStandard SQL nests function calls in an expression, but it has no function values to compose.
BashIdiom
PowerShellIdiomA PowerShell pipeline passes the output of one command to the next command, and a script block can call two other script blocks. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML is a markup language and has no functions.
CSSDoes not applyCSS functions such as calc() can nest, but they are not values that a style sheet can compose.
Regular expressionsDoes not applyA regular expression has no functions.
  • Python. No compose function in the library. Wikipedia shows a compose built with functools.reduce1. reduce "Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value."6
  • JavaScript. No compose function. "In JavaScript we can define it as a function which takes two functions f and g, and produces a function"1. A proposal adds a pipe operator |>, and the README gives its stage as 27.
  • TypeScript. The same as JavaScript. Type parameters give the types of a generic compose: "In TypeScript, generics are used when we want to describe a correspondence between two values."8
  • Java. java.util.function.Function has compose and andThen. compose "Returns a composed function that first applies the before function to its input, and then applies this function to the result."5 andThen "Returns a composed function that first applies this function to its input, and then applies the after function to the result."5
  • C#. No compose operator. "In C# we can define it as an Extension method which takes Funcs f and g, and produces a new Func"1.
  • C. "In languages such as C, the only way to create a new function is to define it in the program source, which means that functions can't be composed at run time."1 A program can still apply an array of function pointers in order1.
  • C++. No compose function for plain functions. A lambda can capture two functions and call them. The ranges library composes views: "Adaptors can be composed into pipelines, so that their actions take place as the view is iterated."9
  • Go. A function that returns a function literal. "Function literals are closures: they may refer to variables declared in a surrounding function."10
  • Rust. A function that returns a closure. The return type uses impl Fn, as in fn returns_closure() -> impl Fn(i32) -> i3211.
  • Bash. Bash functions are not values, but a pipeline joins commands: "The output of each command in the pipeline is connected via a pipe to the input of the next command."12
  • Haskell and F#. Haskell has the operator .4. F# has >> and <<: "The composition operator >> takes two functions and returns a function; by contrast, the pipeline operator |> takes a value and a function and returns a value."13
PythonGitHub
from functools import reduce


def compose(f, g):
    return lambda x: f(g(x))


def compose_all(*fs):
    return reduce(compose, fs, lambda x: x)


def inc(x):
    return x + 1


def double(x):
    return x * 2


print(compose(double, inc)(5))
print(compose(inc, double)(5))
print(compose_all(inc, double, inc)(5))
Output
12
11
13
  • Verdict: idiom. Python has no compose function or operator. A lambda that calls f(g(x)) composes two functions, and functools.reduce with the identity function composes a list of them.
#include <iostream>

auto compose = [](auto f, auto g) {
    return [=](auto x) { return f(g(x)); };
};

int main() {
    auto inc = [](int x) { return x + 1; };
    auto twice = [](int x) { return x * 2; };

    std::cout << compose(twice, inc)(5) << '\n';
    std::cout << compose(inc, twice)(5) << '\n';
    std::cout << compose(inc, compose(twice, inc))(5) << '\n';
}
Output
12
11
13
  • Verdict: idiom. The standard library has no compose function for plain functions. A generic lambda returns a lambda that captures f and g by copy and calls both.
JavaGitHub
import java.util.List;
import java.util.function.Function;

public class Main {
    public static void main(String[] args) {
        Function<Integer, Integer> inc = x -> x + 1;
        Function<Integer, Integer> twice = x -> x * 2;

        System.out.println(twice.compose(inc).apply(5));
        System.out.println(inc.andThen(twice).apply(5));
        System.out.println(inc.compose(twice).apply(5));

        Function<Integer, Integer> all = List.of(inc, twice, inc).stream()
                .reduce(Function.identity(), Function::andThen);
        System.out.println(all.apply(5));
    }
}
Output
12
12
11
13
  • Verdict: stdlib. Function.compose runs its argument first, and Function.andThen runs its argument last. Function.identity is the start value when a stream reduces a list of functions to one.
#include <stdio.h>

typedef int fn(int);

static int inc(int x) { return x + 1; }

static int twice(int x) { return x * 2; }

/* Applies fs[n-1] first and fs[0] last, as in fs[0](fs[1](...(x))). */
static int compose_apply(fn *fs[], int n, int x) {
    for (int i = n - 1; i >= 0; i--) {
        x = fs[i](x);
    }
    return x;
}

int main(void) {
    fn *a[] = {twice, inc};
    fn *b[] = {inc, twice};
    fn *c[] = {inc, twice, inc};
    printf("%d\n", compose_apply(a, 2, 5));
    printf("%d\n", compose_apply(b, 2, 5));
    printf("%d\n", compose_apply(c, 3, 5));
    return 0;
}
Output
12
11
13
  • Verdict: absent. C cannot make a new function at run time, so it cannot return the composition of two functions. The program keeps the functions in an array of function pointers and applies them in order.
using System;

static class Fn
{
    public static Func<A, C> Compose<A, B, C>(this Func<B, C> f, Func<A, B> g)
    {
        return x => f(g(x));
    }
}

class Program
{
    static void Main()
    {
        Func<int, int> inc = x => x + 1;
        Func<int, int> twice = x => x * 2;

        Console.WriteLine(twice.Compose(inc)(5));
        Console.WriteLine(inc.Compose(twice)(5));
        Console.WriteLine(inc.Compose(twice.Compose(inc))(5));
    }
}
Output
12
11
13
  • Verdict: idiom. C# has no compose operator. The extension method Compose takes two Func delegates and returns a lambda that calls both.
JavaScriptGitHub
const compose = (f, g) => (x) => f(g(x));
const composeAll = (...fs) => (x) => fs.reduceRight((acc, f) => f(acc), x);

const inc = (x) => x + 1;
const double = (x) => x * 2;

console.log(compose(double, inc)(5));
console.log(compose(inc, double)(5));
console.log(composeAll(inc, double, inc)(5));
Output
12
11
13
  • Verdict: idiom. JavaScript has no compose function or operator. An arrow function that returns an arrow function composes two functions, and reduceRight applies a list of functions from the last to the first.
TypeScriptGitHub
function compose<A, B, C>(f: (b: B) => C, g: (a: A) => B): (a: A) => C {
  return (x) => f(g(x));
}

const inc = (x: number): number => x + 1;
const double = (x: number): number => x * 2;
const len = (s: string): number => s.length;

console.log(compose(double, inc)(5));
console.log(compose(inc, double)(5));
console.log(compose(inc, compose(double, len))("hello"));
Output
12
11
11
  • Verdict: idiom. TypeScript has no compose function. The type parameters A, B and C make the compiler check that f accepts what g returns, so compose(double, len) takes a string and gives a number.
package main

import "fmt"

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 inc(x int) int { return x + 1 }

func twice(x int) int { return x * 2 }

func main() {
	fmt.Println(compose(twice, inc)(5))
	fmt.Println(compose(inc, twice)(5))
	fmt.Println(compose(inc, compose(twice, inc))(5))
}
Output
12
11
13
  • Verdict: idiom. Go has no compose function. A generic function returns a function literal that captures f and g.
RustGitHub
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 inc(x: i32) -> i32 {
    x + 1
}

fn twice(x: i32) -> i32 {
    x * 2
}

fn main() {
    println!("{}", compose(twice, inc)(5));
    println!("{}", compose(inc, twice)(5));
    println!("{}", compose(inc, compose(twice, inc))(5));
}
Output
12
11
13
  • Verdict: idiom. The standard library has no compose function. A generic function returns a move closure that owns f and g, and the return type impl Fn(A) -> C hides the type of the closure.
BashGitHub
inc() {
  local x
  read -r x
  echo $((x + 1))
}

twice() {
  local x
  read -r x
  echo $((x * 2))
}

echo 5 | inc | twice
echo 5 | twice | inc
echo 5 | inc | twice | inc
Output
12
11
13
  • Verdict: idiom. Bash functions are not values. Each function reads its input and writes its result, and a pipeline connects them from left to right.
  • Right to left or left to right. f ∘ g and Haskell f . g run g first24. F# >> and Java andThen run the left function first135. In F#, addOne << timesTwo applied to 2 gives 5, and addOne >> timesTwo gives 613.
  • Pipelines. A pipeline passes a value through a chain of functions. Wikipedia says that functions on a stream "are known as filters, and are instead connected in a pipeline, which is analogous to function composition and can execute concurrently."1 See Collection pipeline.
  • Stack languages. "In a stack-based language, functional composition is even more natural: it is performed by concatenation, and is usually the primary method of program design."1
  • Currying. Composition joins functions of one argument. Currying turns a function of several arguments into a chain of one-argument functions. See Currying and partial application.
  • Object composition. Composition of objects is a different idea. See Composition over inheritance.

Pitfalls

The wrong order

compose(f, g) runs g first. A program that reads the arguments from left to right gets the steps in the wrong order:

This code runs but gives a wrong answer on purpose.

def compose(f, g):
    return lambda x: f(g(x))


def inc(x):
    return x + 1


def double(x):
    return x * 2


inc_then_double = compose(inc, double)
print(inc_then_double(5))
Output
11

The name means to add 1 and then double, which gives 12. The function doubles and then adds 1, so it gives 11. Write compose(double, inc), or use a left-to-right form such as Java andThen or F# >>513. Composition is "not commutative"2, so the order always matters.

Too much nesting

A long chain of nested calls is hard to read. Wikipedia warns that "A nesting of too many functions may have the opposite effect, making the code less maintainable."1 Give names to the steps, or use a pipeline form that reads from left to right.

Functions with more than one argument

compose gives one value to the next function. A function that needs two arguments does not fit in the chain. Fix one argument with a lambda, or curry the function. See Currying and partial application.

Cost

A composed function of n functions makes n calls and one call to the wrapper for each composition. A composition at run time also makes a new function value, often a closure that holds the two functions10. Haskell defines . with one lambda4, so the operator adds only that call.

References

  1. Function composition (computer science), Wikipedia, the introduction; Composing function calls; Naming the composition of functions; First-class composition
  2. Function composition, Wikipedia, the introduction; Properties; Alternative notations
  3. Structure and Interpretation of Computer Programs, second edition, Abelson and Sussman, 1.3.4 Procedures as Returned Values, Exercise 1.42
  4. Haskell 2010 Language Report, Chapter 9, Standard Prelude, 9.1 The Prelude PreludeList, the definitions of id and (.)
  5. Interface Function, Java SE 25 API, compose; andThen; identity
  6. functools, The Python Standard Library, functools.reduce
  7. Pipe Operator for JavaScript, TC39 proposal, the README, Why a pipe operator
  8. More on Functions, The TypeScript Handbook, Generic Functions
  9. Ranges library, C++ reference, cppreference.com, the introduction; Example
  10. The Go Programming Language Specification, Function literals
  11. Advanced Functions and Closures, The Rust Programming Language, Returning Closures
  12. Pipelines, Bash Reference Manual, 3.2.3 Pipelines
  13. Functions, F# Language Reference, Function composition; Pipelines

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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • the section History