Composition

What is Composition?

You have two functions. You chain them — the output of the first becomes the input to the second.

f:A→B,g:B→Cf: A \to B, \quad g: B \to C

Composition: g∘fg \circ f

This reads: “g of f” or “g after f”


How It Works

(g∘f)(x)=g(f(x))(g \circ f)(x) = g(f(x))

First apply ff, then apply gg to the result.


Example

f(x)=x+1f(x) = x + 1 g(x)=x2g(x) = x^2

Find (g∘f)(2)(g \circ f)(2):

  1. First: f(2)=2+1=3f(2) = 2 + 1 = 3
  2. Then: g(3)=32=9g(3) = 3^2 = 9

(g∘f)(2)=9(g \circ f)(2) = 9


Order Matters

g∘f≠f∘gg \circ f \neq f \circ g

Same functions, different order:

(g∘f)(2)=g(f(2))=g(3)=9(g \circ f)(2) = g(f(2)) = g(3) = 9

(f∘g)(2)=f(g(2))=f(4)=5(f \circ g)(2) = f(g(2)) = f(4) = 5

Different results.

Always apply the inner function first.


Domain Requirements

For g∘fg \circ f to exist:

  • The codomain of ff must match the domain of gg
  • Otherwise, outputs of ff can’t be inputs to gg

f:A→B,g:B→C,g∘f:A→Cf: A \to B, \quad g: B \to C, \quad g \circ f: A \to C


Properties

Associativity:

(h∘g)∘f=h∘(g∘f)(h \circ g) \circ f = h \circ (g \circ f)

Grouping doesn’t matter when composing three functions.

Identity function:

idA(x)=x\text{id}_A(x) = x

f∘idA=ff \circ \text{id}_A = f idB∘f=f\text{id}_B \circ f = f

Composing with identity changes nothing.