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

问题描述

我试图理解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 :: ()

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

解决方法

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

,

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

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

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...