Haskell 哈斯克尔理解单子

Haskell 哈斯克尔理解单子,haskell,monads,Haskell,Monads,只是想让我的头绕过monads 现在看看这一页: 在底部,它询问这些代码片段解析为什么: 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) ) 我理解这一点。是的,因为呼叫失败。看看Monad type

只是想让我的头绕过monads

现在看看这一页:

在底部,它询问这些代码片段解析为什么:

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) )

我理解这一点。

是的,因为呼叫失败。看看Monad typeclass的一个实例:


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
类中的monad,您可以使用
fail
返回
mzero
,即
monad中的


实际上,我不建议使用
fail
,因为它的作用还不清楚。取而代之的是,使用你所处的单子的适当失效机制,无论是
mzero
throwError
还是其他什么。

在Haskell中,你通常可以通过内联和术语重写来理解一些代码:

我们有:

Prelude> Just 0 >>= (\ x -> if (x == 0) then fail "zero" else Just (x + 1) )
Nothing
我们需要的最重要的是为
Maybe
单子定义
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

这就是你要的。

谢谢大家的确认和解释:)注意。你可以通过以下方式找到这一点:点击指向文档的正确超链接,然后单击该页面上的“源”链接,通常在右上角。
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