首页 > 解决方案 > 检查第一个参数中的所有元素是否出现在第二个参数中

问题描述

我从我的代码中得到了错误的结果。

我想检查第一个参数列表中的元素是否出现在第二个参数列表中,并且我使用了这个问题中的代码检查,如果列表是另一个列表的子列表,但我没有得到想要的结果。

del :: Eq t => [t] -> [t] -> Bool
del [] [] = True 
del _ []  = False 
del [] _  = True
del (x:xs) (y:ys)
    | x == y    = del xs ys
    | otherwise = del (x:xs) ys
del [2,3] [3,3,1]  -- should return False, which it does, but 
del "cbbbc" "bca"  -- should return True, but instead it returns False

我不明白为什么?

标签: haskell

解决方案


"cbbbc"不是 的子列表"bca",这意味着列表"cbbbc"不会出现在 内部"bca",例如,"ca"会出现。你的问题是另一个问题。这是一个工作代码,时间复杂度为 O(n):

del :: Eq a => [a] -> [a] -> Bool
del xs ys = all (`elem` ys) xs

这意味着:True如果(且仅当),对于每个xin xsx都是 的元素,则返回ys


推荐阅读