Reputation: 29
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.
Upvotes: 2
Views: 182
Reputation: 71075
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).
Upvotes: 6
Reputation: 3237
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.
Upvotes: 1