(x:_) 和 [x:_] 是什么意思?

发布于 2024-10-08 11:45:20 字数 426 浏览 3 评论 0原文

head' :: [a] -> a
head' [] = error "No head for empty lists!"
head' (x:_) = x

head' :: [a] -> a
head' xs = case xs of [] -> error "No head for empty lists!"
                      (x:_) -> x

我问一个我不明白的相当简单的问题。 在上面的代码中,我看到它需要一个列表作为输入。 但在第三行,它说 (x:_) 这让我很困惑。 谁能向我解释为什么他们写的是 (x:_) 而不是 [x:_]

另外,我不明白 (x:_) 是什么意思。

谢谢。

head' :: [a] -> a
head' [] = error "No head for empty lists!"
head' (x:_) = x

head' :: [a] -> a
head' xs = case xs of [] -> error "No head for empty lists!"
                      (x:_) -> x

I am asking for a fairly easy question which I don't understand.
In the code above, I see that it takes a list for an input.
But on the third line, it says (x:_) which confuses me.
Can anyone explain to me why they wrote (x:_) instead of [x:_]?

And plus, I don't understand what (x:_) means.

Thank you.

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

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

发布评论

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

评论(2

樱花落人离去 2024-10-15 11:45:20

: 是列表的构造函数,它将新列表的头作为其左参数,尾部作为其右参数。如果您将其用作像这里这样的模式,则意味着您匹配的列表的头部被赋予左侧模式,尾部被赋予右侧。

因此,在这种情况下,列表的头部存储在变量 x 中,并且尾部不被使用(_ 意味着您不关心该值)。

是的,您还可以使用 [] 对列表进行模式匹配,但仅限于固定大小的列表。例如,模式 [x] 与仅包含一个元素的列表匹配,然后将该元素存储在变量 x 中。同样,[x,y] 将匹配具有两个元素的列表。

因此,您建议的模式[x:y] 将匹配一个包含一个元素的列表,该元素与模式x:y 匹配。换句话说,它将匹配仅包含一个列表的列表列表。

: is a constructor for lists, which takes the head of the new list as its left argument and the tail as its right argument. If you use it as a pattern like here that means that the head of the list you match is given to the left pattern and the tail to the right.

So in this case the head of the list is stored in the variable x and the tail is not used (_ means that you don't care about the value).

And yes, you can also use [] to pattern match against lists, but only lists of fixed size. For example the pattern [x] matches a list with exactly one element, which is then stored in the variable x. Likewise [x,y] would match a list with two elements.

Your proposed pattern [x:y] would thus match a list with one element, which matches the pattern x:y. In other words, it would match a list of lists which contains exactly one list.

清醇 2024-10-15 11:45:20

这是一个称为模式匹配的概念。 : 是一个中缀构造函数,就像 + 是一个中缀函数一样。在 Haskell 中,您可以与构造函数进行模式匹配。

(1 : 2 : 3 : [])

[1, 2, 3]相同,方括号符号只是创建列表的语法糖。

您的模式 (x : _) 意味着您希望将列表的第一个元素绑定到 x 并且您不关心列表的其余部分 _

This is a concept called pattern matching. : is an infix constructor, just like + is an infix function. In Haskell you pattern match with constructors.

(1 : 2 : 3 : [])

Is the same as [1, 2, 3], the square bracket notation is just syntactic sugar for creating lists.

Your pattern (x : _) means that you want to bind the first element of the list to x and that you do not care about the rest of the list _.

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