# 2.6 Function composition

## 2.6.1 Definition of function composition

Suppose you have two functions $f:X\to Y$ and $g:Y\to Z$:

 $X\stackrel{{\scriptstyle f}}{{\to}}Y\stackrel{{\scriptstyle g}}{{\to}}Z$

Then you can make a new function $X\to Z$ whose rule is “do $f$, then do $g$”.

###### Definition 2.6.1.

Let $f:X\to Y$ and $g:Y\to Z$. The composition of $g$ and $f$, written $g\circ f$ or $gf$, is the function $X\to Z$ with rule $(g\circ f)(x)=g(f(x))$.

This makes sense because $f(x)$ is an element of $Y$ and $g$ has domain $Y$ so we can use any element of $Y$ as an input to $g$.

It’s important to remember that $g\circ f$ is the function whose rule is “do $f$, then do $g$”.

###### Proposition 2.6.1.

If $f:X\to Y$ then $f\circ\operatorname{id}_{X}=\operatorname{id}_{Y}\circ f=f$.

###### Proof.

For any $x\in X$ we have $(f\circ\operatorname{id}_{X})(x)=f(\operatorname{id}_{X}(x))=f(x)$ and $(\operatorname{id}_{Y}\circ f)(x)=\operatorname{id}_{Y}(f(x))=f(x)$. ∎

## 2.6.2 Associativity

Functions $f$ and $g$ such that the codomain of $f$ equals the domain of $g$, in other words, functions such that $g\circ f$ makes sense, are called composable. Suppose that $f$ and $g$ are composable and $g$ and $h$ are also composable, so that we can draw a diagram

 $X\stackrel{{\scriptstyle f}}{{\to}}Y\stackrel{{\scriptstyle g}}{{\to}}Z% \stackrel{{\scriptstyle h}}{{\to}}W.$

It seems there are two different ways to compose these three functions: you could first compose $f$ and $g$, then compose the result with $h$, or you could compose $g$ with $h$ and then compose the result with $f$. But they both give the same result, because function composition is associative.

###### Lemma 2.6.2.

Let $f:X\to Y,g:Y\to Z,h:Z\to W$. Then $h\circ(g\circ f)=(h\circ g)\circ f$.

###### Proof.

Both $h\circ(g\circ f)$ and $(h\circ g)\circ f$ have the same domain $X$, same codomain $W$, and same rule that sends $x$ to $h(g(f(x)))$. ∎

The associativity property says that a composition like $h\circ g\circ f$ doesn’t need any brackets to make it unambiguous: however you bracket it, the result is the same. In fact we can omit brackets from a composition of any length without ambiguity.