[英]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的相应失败机制,无论是mzero
, throwError
还是其他东西。
是的,因为失败的电话。 看看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.