Haskell 理解单子(monad)

标签 haskell monads

只是想让我的头脑了解 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/

相关文章:

haskell - 避免 Haskell 中的分配

operators - SML 选项 Monad(绑定(bind)运算符不起作用)

Haskell `forever` 类型签名

haskell - 在 emacs 上使用 Hlint 和 intero

haskell - haskell-stack 出现奇怪的错误。它不再安装任何东西

scala - 第二单子(monad)定律 :Unit

haskell - liftM2的懒人版

haskell - 类似于 (>>=) 的函数,但返回不同的 monad

haskell - 包含函数的数据类型的仿函数实例

haskell - 类型约束 : Can they be inferred from the datatype of a function's arguments?