首页 > 解决方案 > 在 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]. 我这样做正确吗?

标签: haskell

解决方案


我认为您只需要正确编写递归函数(在此处检查集合相等性)即可完成两件事:基本情况和递归情况。

您的基本情况不正确。你不知道空集[]等于任意集_,除非它也是空的。所以应该是:

setEqual []    []                    = True

加上那个空集不等于其他任何东西:

setEqual []    _                    = False
setEqual _    []                    = False

(请注意,该setEqual [] [] ...行优先,因为它写在其他行之前。

您的递归案例有错字,最后一行应该是:

| otherwise = setEqual a' b

推荐阅读