模式匹配需要非空列表的圆括号,而不是方括号 [英] Pattern matching expects round braces for non empty list and not square brackets

查看:110
本文介绍了模式匹配需要非空列表的圆括号,而不是方括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Haskell中,为什么模式匹配期望列表具有圆括号但不是空方括号时?为什么它在尝试使用空列表[](方括号)进行模式匹配时不遵循相同的约定。不应该圆括号保留专门为元组吗?



例如 - 下面不工作

  third :: Integral a => [a]  - > 
third xs = case xs of
[] - > 0
[_:_:x:_] - > x
其他 - > 0

但是这个工作

  third :: Integral a => [a]  - > 
third xs = case xs of
[] - > 0
(_:_:x:_) - > x
其他 - > 0


解决方案

实际上有办法写一个列表

  [1,2,3] 



  1:2:3:[] 

(注意结尾处的:[] )。第一个是写一个列表的传统方式,但实际上只是编写第二个列表的一个捷径。 表示cons运算符, [] 表示一个空列表(与[] 3:[] 表示,取3并将其前置到空列表中(然后相当于[3])。 / code> 2:3:[] 意思是:在前面的列表前加2(这也等于2:[3] 。最后 1:2:3:[] 相当于 1:[2,3] 。 b

  [1,2,3] 
1:[2,3]
1:2:[3]
1:2:3:[]

是等价的,但 [1: 2:3:[]] 相当于 [[1,2,3]] 不是 [1,2 ,3]



所以,当你在(x:_),你的意思是:我想要一个以 x 开始的列表,我不关心它的尾部(因此它可以是任意长度)当你写 [x:_] ,你实际上正在写 [(x:_)] ,这意味着我想要一个列表ONE元素,这个元素以<$ c开头$ C> X 。这可能是正确的,但是模式匹配的列表不是一个列表,而是一个列表( [[a]] ),它不包含匹配您的类型签名。


In Haskell why pattern matching expects list to have round braces but not square braces when it is not empty? Why does it not follow the same convention when it tries to pattern match with empty list [] (square braces). Shouldn't the round braces reserved exclusively for tuples?

For example - below does not work

third :: Integral a => [a] -> a
third xs = case xs of 
                      [] -> 0
                      [_:_:x:_] -> x
                      otherwise -> 0

But this works

third :: Integral a => [a] -> a
third xs = case xs of 
                      [] -> 0
                      (_:_:x:_) -> x
                      otherwise -> 0

解决方案

There is actually to way to write a list

[1, 2, 3]

Or

1:2:3:[]

(Note the :[] at the end). The first one is the traditional way of writing a list but is actually just a shortcut to write the second one. : denotes the cons operator and [] denotes an empty list (which appears to be the same as []in the first version).3:[]means , take 3 and prepend it to the empty list (which is then equivalent to [3]).2:3:[]means : prepend 2 to the previous list (which is also equivalent to 2:[3]. And finally 1:2:3:[] is equivalent to 1:[2,3]. So

[1, 2, 3]
1:[2,3]
1:2:[3]
1:2:3:[]

are equivalent. However [1:2:3:[]] is equivalent to [[1,2,3]] not [1,2,3].

So, when you pattern match on (x:_), you are saying : I want a list starting with x and I don't care of it's tail (therefore it can be ANY length). When you write [x:_], you are actually writting [(x:_)], which means, I want a list of ONE elements, this element start with x. This could be correct, but the list you are pattern matching on is not a list of a but a list of list of a ([[a]]) which doesn't match your type signature.

这篇关于模式匹配需要非空列表的圆括号,而不是方括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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