对空列表的 head 和 tail 调用会引发异常

发布于 2024-09-15 20:36:47 字数 280 浏览 1 评论 0原文

我正在遵循教程。 (真实世界的 Haskell)

我有一个关于空列表上调用的头和尾的初学者问题:在 GHCi 中它返回异常。

直觉上我想我会说他们都应该返回一个空列表。你能纠正我吗?为什么不呢? (据我记得,在 OzML 中,空列表的左侧或右侧返回 nil)

我肯定还没有在教程中涵盖这个主题,但这不是错误的来源(如果不提供参数)吗? 我的意思是,如果向函数传递一个可能是可选的参数列表,用 head 读取它们可能会导致错误?

我只知道 GHCi 的行为,我不知道编译时会发生什么。

I'm following a tutorial. (Real World Haskell)

And I have one beginner question about head and tail called on empty lists: In GHCi it returns exception.

Intuitively I think I would say they both should return an empty list. Could you correct me ? Why not ? (as far as I remember in OzML left or right of an empty list returns nil)

I surely have not yet covered this topic in the tutorial, but isnt it a source of bugs (if providing no arguments)?
I mean if ever passing to a function a list of arguments which may be optionnal, reading them with head may lead to a bug ?

I just know the GHCi behaviour, I don't know what happens when compiled.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

阪姬 2024-09-22 20:36:47

直觉上我认为他们都应该返回一个空列表。你能纠正我吗?为什么不呢?

好吧 - head[a] ->一个。它返回单个第一个元素;没有清单。

当没有第一个元素时,就像在空列表中一样?那么返回什么?您无法从无到有创建 a 类型的值,因此剩下的就是 undefined - 一个错误。


还有尾巴? Tail 基本上是一个没有第一个元素的列表 - 即比原始元素短的一个项目。当没有第一要素时,你就无法遵守这些法则。

当你从盒子里取出一个苹果时,你不可能拥有同一个盒子(当 tail [] == [] 时发生了什么)。该行为也必须是未定义


由此得出以下结论:

我当然还没有在教程中讨论这个主题,但这不是错误的来源吗?我的意思是,如果向函数传递一个可能是可选的参数列表,用 head 读取它们可能会导致错误?

是的,它是错误的来源,但因为它允许编写有缺陷的代码。基本上尝试读取不存在的值的代码。所以: *永远不要使用头/尾** - 使用模式匹配。

sum     [] = 0
sum (x:xs) = x + sum xs

编译器可以保证 涵盖了所有可能的情况,值总是被定义,并且读起来更清晰。

Intuitively I think would say they both should return an empty list. Could you correct me ? Why not ?

Well - head is [a] -> a. It returns the single, first element; no list.

And when there is no first element like in an empty list? Well what to return? You can't create a value of type a from nothing, so all that remains is undefined - an error.


And tail? Tail basically is a list without its first element - i.e. one item shorter than the original one. You can't uphold these laws when there is no first element.

When you take one apple out of a box, you can't have the same box (what happened when tail [] == []). The behaviour has to be undefined too.


This leads to the following conclusion:

I surely have not yet covered this topic in the tutorial, but isnt it a source of bugs ? I mean if ever passing to a function a list of arguments which may be optionnal, reading them with head may lead to a bug ?

Yes, it is a source of bugs, but because it allows to write flawed code. Code that's basically trying to read a value that doesn't exist. So: *Don't ever use head/tail** - Use pattern matching.

sum     [] = 0
sum (x:xs) = x + sum xs

The compiler can guarantee that all possible cases are covered, values are always defined and it's much cleaner to read.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文