Why is `compose` right to left?

I’ve been working my way through the excellent Mostly Adequate Guide to Functional Programming recently. Although I’ve been working with compose for a bit now, I needed to review why it operates from right-to-left (also known as “right associative”). A review of mathematical theory will help answer this question.

Function Composition

functional composition

The image above is read as “g ∘ f”, or “g composed with f”, or “g-compose-f”. For example, (g ∘ f )(c) = #. If we change ‘c’ to ‘x’, this function would read as g(f(x)). As you’ll remember from high school algebra and composite functions, this means you plug in something for ‘x’, then plug that value into ‘f’, then plug that value into ‘g’. This evaluation occurs from right to left, hence why compose is right associative.

To illustrate compose, consider the following:
f(x) = 2x + 2 and g(x) = –x + 3, find (g o f)(1)
(g o f)(1) = g(f(1))
f(1) = 2(1) + 2 = 4
g(4) = -4 + 3 = -1 (remember, 4 was return value of f(1))
…and -1 is our answer from this function composition.

Left to Right

Developers don’t always think in right-to-left fashion, so if you want the reverse pipe (or sequence depending on the library), is an alternative to compose that operates from left-to-right.




Leave a Reply

Your email address will not be published. Required fields are marked *