Mathematically the function composition operation is associative. Hence:
f . (g . h) = (f . g) . h
Thus the function composition operation may be defined to be either left associative or right associative.
Since normal function application in Haskell (i.e. the juxtaposition of terms, not the $
operation) is left associative in my opinion function composition should also be left associative. After all most people in the world (including myself) are used to reading from left to right.
Nevertheless function composition in Haskell is right associative:
infixr 9 .
I know that it doesn't really make a difference whether the function composition operation is left associative or right associative. Nevertheless I'm curious to know why is it not left associative. Two reasons come to my mind for this design decision:
- The makers of Haskell wanted function composition to be logically as similar as the
$
operation. - One of the makers of Haskell was a Japanese who found it more intuitive to make function composition right associative instead of left associative.
Jokes aside, is there any beneficial reason for function composition to be right associative in Haskell? Would it make any difference if function composition in Haskell was left associative?
$
operation should be right associative either. However right associativity is not always wrong. For example the++
operation and the logical operations&&
and||
must clearly be right associative so that concatenation cost is minimal and so that logical expressions may be short circuited, respectively. – Jannjanna$
isn't associative. It has different semantics if you change it to aninfixl
definition. And those different semantics would probably be better. But since.
is associative, the semantics are the same either way - all that changes is operational details, whereinfixr
is definitely better. – Dmso