简体   繁体   English

Haskell:检查两个列表是否相等

[英]Haskell: check if two lists are equal

I want to check if two lists A and B are equal, ie, a1 == b1, a2 == b2 ,... 我想检查两个列表AB是否相等,即a1 == b1, a2 == b2 ,...

I have a working solution: 我有一个有效的解决方案:

all (\x->x) zipWith $ (==) A B

Another idea is to do it recursively: a:as, b:bs ; 另一个想法是递归地做: a:as, b:bs ; check if a1==b1 and call the function with the remaining lists as and bs . 检查a1==b1和调用函数与其余列表asbs But isn't there an easier and more readable way to do this? 但是,有没有更简单,更易读的方法来做到这一点?

You can just use == on them directly. 你可以直接使用==

> [1, 2, 3] == [1, 2, 3]
True
> [1, 2, 3] == [1, 2]
False

This is because == is part of the Eq type class, and there is an Eq instance for lists which looks something like this: 这是因为==Eq类型类的一部分,并且列表的Eq实例看起来像这样:

instance Eq a => Eq [a]

This means that lists instantiate Eq as long as the element type also instantiates Eq , which is the case for all types defined in the standard Prelude except functions and IO actions. 这意味着,列出了实例Eq只要元素类型还实例化Eq ,这是在除了功能和标准前奏曲定义的所有类型的情况下IO动作。

First, hammar's answer is correct, so accept his answer please. 首先,哈马尔的回答是正确的,所以请接受他的回答。 (Edit: Which you have done, thank you.) (编辑:你做过的,谢谢。)

listA == listB

(I'm going to nitpick on small details in your question, mostly for the benefit of future beginners who find this page on Google.) (我将挑选你问题中的小细节,主要是为了在Google上找到这个页面的未来初学者的利益。)

Second, A and B aren't lists: they start with upper case letters, so they cannot be variables. 其次, AB不是列表:它们以大写字母开头,因此它们不能是变量。 I'm going to call them listA and listB instead. 我打算将它们listAlistB

Third, there is a typo in your working solution: the $ should be before the zipWith , not after. 第三,你的工作解决方案中有一个拼写错误: $应该在zipWith之前,而不是之后。 The way it appears in your question results in a compile error. 它出现在您的问题中的方式导致编译错误。 I think you meant this: 我想你的意思是:

all (\x->x) $ zipWith (==) listA listB

Fourth, (\\x->x) is better known as the function id . 第四, (\\x->x)更好地称为函数id

all id $ zipWith (==) listA listB

Fifth, as Matvey points out, all id is the same as and . 第五,Matvey指出, all idand

and $ zipWith (==) listA listB

Sixth, these do different things when the lists have different lengths. 第六,当列表具有不同的长度时,这些做不同的事情。 Using (==) directly on lists will result in False , whereas zipWith will ignore the excess elements. 直接在列表上使用(==)将导致False ,而zipWith将忽略多余的元素。 That is: 那是:

[1,2,3] == [1,2]                   -- False
and $ zipWith (==) [1,2,3] [1,2]   -- True

Now, there are probably situations when you want the second behaviour. 现在,您可能需要第二种行为。 But you almost certainly want the first behaviour. 但你几乎肯定想要第一个行为。

Finally, to emphasise, just use (==) directly on the lists: 最后,要强调,只需在列表上直接使用(==)

listA == listB

您可以替换all (\\x -> x)and

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM