haskell - 检查第一个参数中的所有元素是否出现在第二个参数中
问题描述
我从我的代码中得到了错误的结果。
我想检查第一个参数列表中的元素是否出现在第二个参数列表中,并且我使用了这个问题中的代码检查,如果列表是另一个列表的子列表,但我没有得到想要的结果。
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
这意味着:True
如果(且仅当),对于每个x
in xs
,x
都是 的元素,则返回ys
。
推荐阅读
- r - 使用 conditionalPanel() 和 fileInput() 根据单选按钮输入不同的文件类型
- typescript - 一些接口(例如IUser 或IData)使用“I”作为接口名称的开头,为什么?
- python-3.x - 使用 Selenium 选择单选按钮
- c - 使用 Jansson API 的 json 中的多行“值”
- javascript - 在这个 svg 滚动动画中使用粘性导航
- spring-vault - 将 Spring Cloud Vault 和 ConfigData API 与多个配置文件一起使用
- solidity - Solidity - 基于字符串值哈希的映射
- next.js - 在一个请求中创建多个页面
- amazon-web-services - 雅典娜找到一个月的最后一天
- python - 为什么在输入文件中搜索字符串时会出现“StopIteration”?