Standard Prelude 函数中是否有实现并集和集合交集的功能?
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] 推荐答案有union 和 intersect 函数在标准库中的列表上,位于 Data.List但不在 Prelude 本身中.
就效率而言,我将对以上所有内容说不",无论是您的还是标准库的.在只有 Eq 约束的列表上,真的没有办法进行有效的操作.也就是说,您仍然可以在 Data.List 中找到信息丰富的实现——请参阅上面的链接,我已直接指向相关来源.
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 in Data.List informative--see the links above, which I've pointed directly to the relevant source.
编辑 -- 作为一个简短的附录,以供后人参考,请务必查看 Don 对您实际想要用于此目的的回答,而不是这些功能是否存在"的狭义问题.
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".
更多推荐
是否有联合和相交 Haskell Prelude 实现?
发布评论