17
votes

Without any parentheses :

Prelude> [1,2] >>= \n -> ['a', 'b'] >>= \ch -> return (n, ch)
[(1,'a'),(1,'b'),(2,'a'),(2,'b')]

Parentheses assuming left associativity:

Prelude> ([1,2] >>= \n -> ['a', 'b']) >>= \ch -> return (n, ch)
<interactive>:22:49: Not in scope: `n'

Parentheses assuming right associativity:

Prelude> [1,2] >>= (\n -> ['a', 'b'] >>= \ch -> return (n, ch))
[(1,'a'),(1,'b'),(2,'a'),(2,'b')]

Isn't >>= left associative? When no parentheses are present, why does GHCi evaluate the expression as if >>= is right associative?

1

1 Answers

19
votes

Yes, >>= is left associative. However, lambdas extend as far as possible. So the presence of the \n -> means that the only correct way to parse the expression is as

[1,2] >>= (\n -> ['a', 'b'] >>= \ch -> return (n, ch))

Note that your "left associativity" form

([1,2] >>= \n -> ['a', 'b']) >>= \ch -> return (n, ch)

isn't even scope-correct. The n in the final return is out of scope.