“失败"“零"是在简单的"a->"中不生成任何内容的一种方式.也许是一个例子 [英] `fail "zero"` as a way to generate Nothing in simple `a -> Maybe a` example

查看:69
本文介绍了“失败"“零"是在简单的"a->"中不生成任何内容的一种方式.也许是一个例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读使用绑定运算符的一个生动示例:

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(记录为

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

没事.

这篇关于“失败"“零"是在简单的"a->"中不生成任何内容的一种方式.也许是一个例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆