Haskell Prelude 是否有 union 和 intersect 实现?
标准 Prelude 函数中是否有实现集合的并集和交集?
union :: (Eq a) => [a] -> [a] -> [a]
intersect :: (Eq a) => [a] -> [a] -> [a]
如果不是,有人可以说我的实现是否有效,(充分利用懒惰和前奏功能)
unionSet :: (Eq a) => [a] -> [a] -> [a]
unionSet as bs = foldl (\xs y -> if elem y xs then xs else xs ++ [y]) as bs
intersectSet :: (Eq a) => [a] -> [a] -> [a]
intersectSet as bs = let ns = [ a | a <- as, elem a bs] in [ b | b <- bs, elem b ns]
Is there in the Standard Prelude functions which implement the union and the intersection of sets ?
union :: (Eq a) => [a] -> [a] -> [a]
intersect :: (Eq a) => [a] -> [a] -> [a]
If no, may somebody can said if my implementation is efficient, (make good use of laziness and prelude function)
unionSet :: (Eq a) => [a] -> [a] -> [a]
unionSet as bs = foldl (\xs y -> if elem y xs then xs else xs ++ [y]) as bs
intersectSet :: (Eq a) => [a] -> [a] -> [a]
intersectSet as bs = let ns = [ a | a <- as, elem a bs] in [ b | b <- bs, elem b ns]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有
union< /code>
和
intersect
标准库中列表的函数,位于Data.List
中,但不在Prelude
中本身。就效率而言,我将对上述所有内容说“不”,无论是您的还是标准库的。实际上,仅使用
Eq
约束就无法对列表进行有效的操作。也就是说,您可能仍然会在Data.List
中找到信息丰富的实现 - 请参阅上面的链接,我已直接指向相关源。编辑 - 作为为了后代的简短附录,请务必查看 Don 的答案,了解您实际上想要用于此目的的内容,而不是狭隘的问题“这些功能是否存在”。
There are
union
andintersect
functions on lists in the standard libraries, located inData.List
but not in thePrelude
itself.As far as efficiency goes, I'm going to say "no" to all of the above, both yours and the standard library's. There's really no way either can ever be efficient operations on a list with only an
Eq
constraint. That said, you may still find the implementation inData.List
informative--see the links above, which I've pointed directly to the relevant source.Edit -- As a brief addendum for the sake of posterity, be sure to see Don's answer for what you actually want to use for this purpose, rather than the narrower question of "do these functions exist at all".
正如 camccann 指出的那样,基础库提供了列表版本。如果您想要更高效的东西,请考虑数据.Set,它提供:
复杂度O(n+m)。
The base library provides list versions, as camccann points out. If you want something a bit more efficient, consider Data.Set, which provides:
with complexity O(n+m).