Haskell:检查两个列表是否相等 [英] Haskell: check if two lists are equal

查看:129
本文介绍了Haskell:检查两个列表是否相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查两个列表 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实例列表如下所示:

公式[a]

这意味着列表实例化 Eq 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屋!

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