Blurt

Function Composition

Here be dragons :dragon:

The Haskell wiki explains function composition as

the act of pipelining the result of one function to the input of another, creating an entirely new function

and that seems relatively easy to wrap one’s mind around.

It’s just the associativity that confused me initially :confused:.

In Haskell, I defined two simple functions times3 and plus1

times3 = (*3)
plus1 = (+1)

which I could compose and apply to 2 to yield 7

(plus1 . times3) 2

which is “effectively” equivalent to

plus1 (times3 2)

which demonstrates the piping idea in a manner more palatable to my brain.

The type of the composition operator (.) is defined as $(\beta \to \gamma) \to (\alpha \to \beta) \to \alpha \to \gamma$ which I dumb down to

  • two operands, each being funtions, are composed to produce a new function $\alpha \to \gamma$
  • compositions are processed from the rightmost function towards the left therefore one may state that, regardless how many compositions are chained together:
    • the output type of the leftmost operand (in our simplified expression above, function $\beta \to \gamma$) dictates the return type of the resulting function (or composition) so I guess it makes sense to state that the leftmost function sits at the end of the pipe.
    • the rightmost function represents the first function that will be applied