gpt4 book ai didi

haskell - 检查第一个参数中的所有元素是否出现在第二个参数中

转载 作者:行者123 更新时间:2023-12-02 17:10:30 24 4
gpt4 key购买 nike

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

我想检查第一个参数列表中的元素是否出现在第二个参数列表中,我使用了此问题 Check, if list is a sublist of another list 中的代码但我没有得到想要的结果。

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

我不明白为什么?

最佳答案

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

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

这意味着:当(且仅当)对于 xs 中的每个 x 时,返回 Truexys 的元素。

关于haskell - 检查第一个参数中的所有元素是否出现在第二个参数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58767464/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com