Cogs and Levers A blog full of technical stuff

Function composition in Haskell

Function composition is a no-brainer concept for Haskell that makes a lot of sense. It’s truly aligned with its mathematical equivelant where you have two given functions:

f(x) = x * x
g(x) = x + 2

The composition part comes in when you nest these functions, so that you end up with:

f(g(x)) = f(x + 2)
f(g(x)) = (x + 2) * (x + 2)
f(g(x)) = x^2 + 4x + 4

Mathematically, this is cake. We just nest the second function inside the first. If we look at it with respect to Haskell we end up with this:

-- | g(x) = x + 2
let g x = x + 2

-- | f(x) = x * x
let f x = x * x

-- | f(g(x))
let fg = f . g

So, the . operator is doing the composition here for us. Below I’ve got the mathematical representation on the left, Haskell on the right.

f(g(x)) = (f . g) x

The real power here is that you can use function composition with any two functions, just as long as the return type of the second function is the same as the argument taken by the first function.

Slick.