我试图理解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 :: ()
我不理解它,因为第二个示例与第三个示例相反,因为它似乎与已知的关联性相矛盾。我知道我缺少什么,但我不知道什么。
答案 0 :(得分:3)
根据最大的munch规则,lambda被尽可能地解析到右侧,因此>>=
运算符的左侧关联性没有机会发挥作用。将您的第二个代码段解析为第一个代码段,而不是第三个代码段(当然这是无效的代码)。
答案 1 :(得分:1)
这是因为括号使x
超出了范围:
(Just 3 >>= \x -> Just "!" ) >>= \y -> Just (show x ++ y)
(Just 3 >>= \x -> Just "!" )
将变为Just "!"
,而x
将超出范围。