问题描述
我正在阅读使用绑定运算符的一个生动示例:
Just 5 >>= (\ x -> if (x == 0) then fail "zero" else Just (x + 1) )
返回Just 6
.
我对fail
的行为及其在示例中的有用性感到困惑.在查看代码时,我认为fail "zero"
可能具有含义:
I'm confused by the behaviour of fail
and its usefulness in the example.When looking at the code I thought fail "zero"
may have a meaning:
- 程序永远无法达到目的
- 懒惰
- 其他.
然后我意识到,在类型凝聚后,异常变为Nothing
(记录为此处).仍然令我感到困惑的是,没有类型强制fail
只是程序中的错误.
Then I realised that after a type cohesion, an exception becomes Nothing
(documented here). Still confusing for me that without type enforcement fail
is just an error in program.
Prelude> fail "zero" :: Maybe Int
Nothing
Prelude> fail "abc" :: [Int]
[]
Prelude> fail "zero"
*** Exception: user error (zero)
在本示例中,我的问题是关于fail "zero"
的用途.
My question is about usefulness of fail "zero"
in this example.
对于a -> Maybe a
函数来说,是否正确读取(\ x -> if (x == 0) then fail "zero" else Just (x + 1) )
试图使其简单化?
Is it a proper reading (\ x -> if (x == 0) then fail "zero" else Just (x + 1) )
attempts to be simple case for a -> Maybe a
function?
如果只是需要a -> Maybe a
的插图,是什么使我们无法使用(\ x -> if (x == 0) then Nothing else Just (x + 1) )
?
What prevents us from using (\ x -> if (x == 0) then Nothing else Just (x + 1) )
if we just needed an illustration of a -> Maybe a
?
我在下面找到了此版本,这是一种更容易,更简短的方法来掌握相同的示例.
I found this version below a much easier and shorter way to grasp same example.
Prelude> g x = if (x == 0) then Nothing else Just (x + 1)
Prelude> Just 0 >>= g
Nothing
Prelude> Just 1 >>= g
Just 2
推荐答案
是的
没事.
这篇关于“失败"“零"是在简单的"a->"中不生成任何内容的一种方式.也许是一个例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!