首页 > 解决方案 > `fail "zero"` 作为在简单的 `a -> Maybe a` 示例中生成 Nothing 的一种方式

问题描述

我正在阅读一个使用绑定运算符的启发性示例

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

返回Just 6

fail对示例中的行为及其有用性感到困惑。在查看代码时,我认为fail "zero"可能有一个含义:

然后我意识到,在类型凝聚之后,一个异常变成了Nothing在此处记录)。仍然让我感到困惑的是,没有类型强制fail只是程序中的一个错误。

Prelude> fail "zero" :: Maybe Int
Nothing
Prelude> fail "abc" :: [Int]
[]
Prelude> fail "zero"
*** Exception: user error (zero)

我的问题是关于fail "zero"这个例子中的有用性。

简单的功能案例是正确的阅读(\ x -> if (x == 0) then fail "zero" else Just (x + 1) )尝试a -> Maybe a吗?

(\ x -> if (x == 0) then Nothing else Just (x + 1) )如果我们只需要一个插图,是什么阻止我们使用 a -> Maybe a

我发现下面的这个版本更容易和更短地掌握相同的例子。

Prelude> g x = if (x == 0) then Nothing else Just (x + 1)
Prelude> Just 0 >>= g
Nothing
Prelude> Just 1 >>= g
Just 2

标签: haskellmonads

解决方案


简单的功能案例是正确的阅读(\ x -> if (x == 0) then fail "zero" else Just (x + 1) )尝试a -> Maybe a吗?

是的。

(\ x -> if (x == 0) then Nothing else Just (x + 1) )如果我们只需要一个插图,是什么阻止我们使用 a -> Maybe a

没有什么。


推荐阅读