了解Haskell中Monad的bind运算符的关联性

时间:2020-10-17 20:36:08

标签: haskell operators bind monads operator-precedence

我试图理解Monad的bind运算符的工作原理,但是发现了一个奇怪的例子,因为考虑到>>= left -关联。这是在解释器提示下进行测试的示例:

> 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 :: ()

我不理解它,因为第二个示例与第三个示例相反,因为它似乎与已知的关联性相矛盾。我知道我缺少什么,但我不知道什么。

2 个答案:

答案 0 :(得分:3)

根据最大的munch规则,lambda被尽可能地解析到右侧,因此>>=运算符的左侧关联性没有机会发挥作用。将您的第二个代码段解析为第一个代码段,而不是第三个代码段(当然这是无效的代码)。

答案 1 :(得分:1)

这是因为括号使x超出了范围:

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

(Just 3 >>= \x -> Just "!" )将变为Just "!",而x将超出范围。