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))
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
- 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
- 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 - A new function value.
composereturns 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 asf . g = \ x -> f (g x)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
| Language | Verdict | Note |
|---|---|---|
| Python | Idiom | |
| C++ | Idiom | |
| Java | Standard library | |
| C | Absent | |
| C# | Idiom | |
| JavaScript | Idiom | |
| TypeScript | Idiom | |
| Go | Idiom | |
| Rust | Idiom | |
| Kotlin | Idiom | The 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. |
| SQL | Does not apply | Standard SQL nests function calls in an expression, but it has no function values to compose. |
| Bash | Idiom | |
| PowerShell | Idiom | A 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. |
| HTML | Does not apply | HTML is a markup language and has no functions. |
| CSS | Does not apply | CSS functions such as calc() can nest, but they are not values that a style sheet can compose. |
| Regular expressions | Does not apply | A regular expression has no functions. |
- Python. No compose function in the library. Wikipedia shows a
composebuilt withfunctools.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.FunctionhascomposeandandThen.compose"Returns a composed function that first applies the before function to its input, and then applies this function to the result."5andThen"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 infn 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
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))
12
11
13
- Verdict: idiom. Python has no compose function or operator. A lambda that calls
f(g(x))composes two functions, andfunctools.reducewith 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';
}
12
11
13
- Verdict: idiom. The standard library has no compose function for plain functions. A generic lambda returns a lambda that captures
fandgby copy and calls both.
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));
}
}
12
12
11
13
- Verdict: stdlib.
Function.composeruns its argument first, andFunction.andThenruns its argument last.Function.identityis 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;
}
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));
}
}
12
11
13
- Verdict: idiom. C# has no compose operator. The extension method
Composetakes twoFuncdelegates and returns a lambda that calls both.
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));
12
11
13
- Verdict: idiom. JavaScript has no compose function or operator. An arrow function that returns an arrow function composes two functions, and
reduceRightapplies a list of functions from the last to the first.
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"));
12
11
11
- Verdict: idiom. TypeScript has no compose function. The type parameters
A,BandCmake the compiler check thatfaccepts whatgreturns, socompose(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))
}
12
11
13
- Verdict: idiom. Go has no compose function. A generic function returns a function literal that captures
fandg.
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));
}
12
11
13
- Verdict: idiom. The standard library has no compose function. A generic function returns a
moveclosure that ownsfandg, and the return typeimpl Fn(A) -> Chides the type of the closure.
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
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.
Variations and related ideas
- Right to left or left to right.
f ∘ gand Haskellf . grungfirst24. F#>>and JavaandThenrun the left function first135. In F#,addOne << timesTwoapplied to 2 gives 5, andaddOne >> timesTwogives 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))
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
- Function composition (computer science), Wikipedia, the introduction; Composing function calls; Naming the composition of functions; First-class composition
- Function composition, Wikipedia, the introduction; Properties; Alternative notations
- Structure and Interpretation of Computer Programs, second edition, Abelson and Sussman, 1.3.4 Procedures as Returned Values, Exercise 1.42
- Haskell 2010 Language Report, Chapter 9, Standard Prelude, 9.1 The Prelude PreludeList, the definitions of id and (.)
- Interface Function, Java SE 25 API, compose; andThen; identity
- functools, The Python Standard Library, functools.reduce
- Pipe Operator for JavaScript, TC39 proposal, the README, Why a pipe operator
- More on Functions, The TypeScript Handbook, Generic Functions
- Ranges library, C++ reference, cppreference.com, the introduction; Example
- The Go Programming Language Specification, Function literals
- Advanced Functions and Closures, The Rust Programming Language, Returning Closures
- Pipelines, Bash Reference Manual, 3.2.3 Pipelines
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag RXZVPN Edit this page History Report an error Markdown