(x:_)和[x:_]是什么意思? [英] What does (x:_) and [x:_] mean?

查看:634
本文介绍了(x:_)和[x:_]是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  head':: [a]  - >一个
头'[] =错误没有空头列表!
head'(x:_)= x

head':: [a] - >
head'xs = case xs of [] - >错误没有空头名单!
(x:_) - > x

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



另外,我不明白(x:_)的意思。



谢谢。

解决方案

是列表的构造函数,它将新列表的头部作为左边参数,将尾部作为其正确参数。如果你将它用作这里的模式,这意味着你匹配的列表的头部被赋予左边的模式,右边的尾部赋予它。



如果列表的头部存储在变量 x 中且未使用尾部( _ 意味着您不用并不在乎价值)。

是的,您也可以使用 [] 模式匹配列表,但只有固定大小的清单。例如,模式 [x] 与一个只包含一个元素的列表匹配,然后存储在变量 x 中。同样, [x,y] 会匹配包含两个元素的列表。 您建议的模式 [x:y] 会因此匹配一个包含一个元素的列表,该元素与模式 x:y 匹配。换句话说,它将匹配包含一个列表的列表。


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.

解决方案

: 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.

这篇关于(x:_)和[x:_]是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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