【问题标题】:Haskell Understanding MonadsHaskell 理解单子
【发布时间】:2012-05-06 19:38:44
【问题描述】:

只是想让我的头脑转转单子......

目前正在查看此页面:http://www.haskell.org/haskellwiki/Simple_monad_examples

在底部询问这些 sn-ps 解析为:

Just 0 >>= (\ x -> if (x == 0) then fail "zero" else Just (x + 1) )

为什么这会返回 Nothing?因为调用失败?

Nothing >>= (\ x -> if (x == 0) then fail "zero" else Just (x + 1) )

这个我明白。

【问题讨论】:

  • 感谢大家的确认和解释:)

标签: haskell monads


【解决方案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

你有它。

【讨论】:

    【解决方案2】:

    fail 的行为取决于 monad。在Maybe monad 中,fail 返回Nothing

    instance Monad Maybe where
      return = Just
    
      (Just x) >>= k = k x
      Nothing  >>= _ = Nothing
    
      fail _ = Nothing
    

    但是,在许多其他 monad 中,fail 转换为 error,因为这是默认实现。提供自己的fail 的monad 通常是MonadPlus 类中的那些,你可以让fail 返回mzero,即Maybe monad 中的Nothing

    在实践中,我不建议使用fail,因为它会做什么还不清楚。相反,请使用您所在的 monad 的适当故障机制,无论是 mzerothrowError 还是其他。

    【讨论】:

      【解决方案3】:

      是的,因为调用失败。看看 Maybe 如何是 Monad 类型类的一个实例:

      http://www.haskell.org/ghc/docs/latest/html/libraries/base/src/Data-Maybe.html#Maybe

      fail _              = Nothing
      

      【讨论】:

      • n.b.您可以通过hoogling Maybe 找到此文档,并点击正确的文档超链接,然后单击该页面上的“源”链接,通常位于右上角。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 1970-01-01
      相关资源
      最近更新 更多