Haskell:检查两个列表是否相等 [英] Haskell: check if two lists are equal
问题描述
我想检查两个列表 A
和 B
是否相等,即 a1 == b1,a2 == b2
,...
我有一个可行的解决方案:
全部(\ x-> x)zipWith $(==)AB
另一个想法是递归执行: a:as,b:bs
;检查 a1 == b1
,然后使用剩余列表作为
和 bs
。但没有一个更简单,更可读的方法来做到这一点?
==
。 > [1,2,3] == [1,2,3]
True
> [1,2,3] == [1,2]
False
这是因为 ==
是 Eq
类型类的一部分,并且有一个 Eq <
$ b $ pre $ code> instance Eq a => code $ c> instance实例列表如下所示:
这意味着列表实例化 Eq $ c $只要元素类型也实例化
Eq
,除了函数和 IO
行动。
I want to check if two lists A
and B
are equal, i.e., 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
; check if a1==b1
and call the function with the remaining lists as
and bs
. 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:
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.
这篇关于Haskell:检查两个列表是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!