Understanding associativity of the Monad's bind operator in Haskell

Viewed 131

I was trying to understanding how the Monad's bind operator works, but found an example which was odd, because the apparent associativity didn't make sense to me considering the fact that >>= is left-associative. Here is the example, testing at an interpreter's prompt:

> Just 3 >>= \x -> Just "!" >>= \y -> Just (show x ++ y)
Just "3!"

> Just 3 >>= (\x -> Just "!" >>= (\y -> Just (show x ++ y)))
Just "3!"

> (Just 3 >>= \x -> Just "!" )>>= \y -> Just (show x ++ y)
<interactive>:3:50: error: Variable not in scope: x :: ()

I don't understand it because the second example runs in opposition to the third, because it seems that it goes in the way which is contradictory to the known associativity. I know that I am missing something, but I don't know what.

2 Answers

According to the maximal munch rule, lambdas are parsed as far to the right as possible, so the left associativity of the >>= operator doesn't have a chance to come into play. It is your second snippet that the first is parsed as, not the third (which of course is an invalid code).

This is because the parenthesis take x out of scope:

(Just 3 >>= \x -> Just "!" ) >>= \y -> Just (show x ++ y)

(Just 3 >>= \x -> Just "!" ) will become Just "!", and x will go out out of scope.

Related