haskell - 在 Haskell 中检查两个列表是否相等
问题描述
我正在尝试创建功能setEqual
..这是我到目前为止所拥有的:
setEqual :: Eq a => [a] -> [a] -> Bool
setEqual [] _ = True
setEqual _ [] = False
setEqual a@(x:a') (y:b) | x == y = setEqual a' b
| otherwise = setEqual a b
setEqualTest = [ not ("ABCD" `setEqual` "ABC"),
not ("ABC" `setEqual` "ABCD"),
[0,2,1,3] `setEqual` [0,1,2,3] ]
当我运行测试时,我得到[True, False, False]
. 我这样做正确吗?
解决方案
我认为您只需要正确编写递归函数(在此处检查集合相等性)即可完成两件事:基本情况和递归情况。
您的基本情况不正确。你不知道空集[]
等于任意集_
,除非它也是空的。所以应该是:
setEqual [] [] = True
加上那个空集不等于其他任何东西:
setEqual [] _ = False
setEqual _ [] = False
(请注意,该setEqual [] [] ...
行优先,因为它写在其他行之前。
您的递归案例有错字,最后一行应该是:
| otherwise = setEqual a' b
推荐阅读
- angular - Angular/NativeScript 应用程序中的单元测试
- powershell - 如何使用输入文件来提供 powershell 命令?
- mysql - 如何使用 sequelize mysql 添加外键
- typescript - 使用枚举作为字典键
- python - 在 python2.7 环境中 conda install basemap 给出运行时错误 R6034
- highcharts - Trying to figure out how to assign specific colors to specific data points in Highchart Pie chart
- sql-server - SQL Server dynamic SQL to query on sys tables
- html - 连续对齐具有不同尺寸的图像
- linux - Putty Search - String followed by one but not two symbols
- javascript - 将所有状态属性传递给函数,除了一个