繁体   English   中英

Haskell了解Monads

[英]Haskell Understanding 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

我们需要的最重要的事情是fail的定义和>>=对于Maybe monad,给出如下:

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

你有它。

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类中的MonadPlus ,你可以fail返回mzero ,这在Maybe monad中是Nothing

在实践中,我不建议使用fail因为它不清楚它会做什么。 相反,使用你所在的monad的相应失败机制,无论是mzerothrowError还是其他东西。

是的,因为失败的电话。 看看Maybe是Monad类型类的一个实例:

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

fail _              = Nothing

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM