F2.08 · part 1 of 3
Function composition
Composing two functions produces a third that runs them in turn: the inner function first, its
result fed to the outer. Written f(g(x)), or f ∘ g,
it is read “f after g.” The composed function is an ordinary function, ready to compose again.
Order is not a detail. f ∘ g and g ∘
f usually differ — adding one then doubling is not doubling then adding one. Composition is, however,
associative: grouping three functions either way gives the same result. And one function leaves any other
unchanged under composition — the identity.
Order matters
Swap the order of two functions and the result generally changes. With inc and
double, composing one way adds then doubles; the other way doubles then adds.
Toggle the order and compare.
- composition
- feeding one function’s output into another:
f(g(x)). - order
- which runs first — the inner function, named last.
- associative
- grouping three either way gives the same result.
- identity
- the function that returns its input unchanged.
f ∘ g versus g ∘ f
Idea
Composition is not commutative: f ∘ g rarely equals g ∘ f.
Elixir
The inner call sits deepest in the parentheses — and runs first.
Swapping composition order usually changes the answer. The inner function, written last, runs first.
Chaining three
Composition extends to any number of functions. Compose inc,
double, and square and a value flows through all three.
Because composition is associative, it does not matter how you group them — the order of the chain is what
counts.
Set the input and follow it through.
square ∘ double ∘ inc · three stages
Idea
A chain of composed functions is itself one function of the input.
F2.08.2 · pipe
The pipe writes this same chain in the order the stages run.
Composition chains to any length. The reading order, inner to outer, is the order of operations.
Worked examples
A compose combinator, the composition rule, the identity, and a three-function chain.