只是想让我的头脑了解 monad...
目前查看此页面:http://www.haskell.org/haskellwiki/Simple_monad_examples
在底部它会询问这些片段解析为什么:
Just 0 >>= (\ x -> if (x == 0) then fail "zero" else Just (x + 1) )
为什么这没有返回?因为调用失败?
Nothing >>= (\ x -> if (x == 0) then fail "zero" else Just (x + 1) )
这个我懂了。
最佳答案
在 Haskell 中,您通常可以通过内联和术语重写来理解一些代码:
我们有:
Prelude> Just 0 >>= (\ x -> if (x == 0) then fail "zero" else Just (x + 1) )
Nothing
我们需要的最重要的事情是 maybe
monad 的 fail
和 >>=
的定义,如下所示:
instance Monad Maybe where
(Just x) >>= k = k x
Nothing >>= _ = Nothing
(Just _) >> k = k
Nothing >> _ = Nothing
return = Just
fail _ = Nothing
所以我们有:
Just 0 >>= (\ x -> if (x == 0) then fail "zero" else Just (x + 1) )
-- by definition of >>=
(\ x -> if (x == 0) then fail "zero" else Just (x + 1) ) 0
-- by definition of fail
(\ x -> if (x == 0) then Nothing else Just (x + 1) ) 0
-- beta reduce
if 0 == 0 then Nothing else Just (0 + 1)
-- Integer math
if True then Nothing else Just 1
-- evaluate `if`
Nothing
好了。
关于Haskell 理解单子(monad),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10473631/