【发布时间】:2019-05-17 18:26:48
【问题描述】:
我正在阅读a revealing example of using a bind operator:
Just 5 >>= (\ x -> if (x == 0) then fail "zero" else Just (x + 1) )
返回Just 6。
我对@987654325@ 的行为及其在示例中的用处感到困惑。
看代码的时候我觉得fail "zero"可能有一个意思:
- 程序永远不会到那个地步
- 懒惰
- 别的东西。
然后我意识到,在类型凝聚之后,异常变为Nothing(记录在here)。仍然让我感到困惑的是,没有类型强制 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 函数的简单案例是否正确?
如果我们只需要 a -> Maybe a 的插图,是什么阻止我们使用 (\ x -> if (x == 0) then Nothing else Just (x + 1) )?
我发现下面的这个版本更容易和更短地掌握相同的例子。
Prelude> g x = if (x == 0) then Nothing else Just (x + 1)
Prelude> Just 0 >>= g
Nothing
Prelude> Just 1 >>= g
Just 2
【问题讨论】: