是否有联合和相交 Haskell Prelude 实现? [英] is there union and intersect Haskell Prelude implementation?

查看:20
本文介绍了是否有联合和相交 Haskell Prelude 实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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]

推荐答案

unionintersect 函数在标准库中的列表上,位于 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 实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆