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

查看:95
本文介绍了是否有联盟和相交Haskell 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 [...],elem a bs]在[b | b< - bs,elem b ns]


解决方案

联合 Data.List 的标准库中的列表上的rel =noreferrer> intersect 但不在 Prelude 本身。



就效率而言,我要说不以上所有的,你和标准的图书馆。在只有 Eq 约束的列表中,确实没有办法有效的操作。也就是说,您可能还会在 Data.List 中找到实现信息 - 请参阅上面的链接,我直接指向相关来源。



编辑 - 作为后代的简要补充,请确保看到唐的答案,使您真正希望使用为此,而不是完全实现这些功能的较窄问题。


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]

解决方案

There are union and intersect functions on lists in the standard libraries, located in Data.List but not in the Prelude 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 in Data.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".

这篇关于是否有联盟和相交Haskell Prelude实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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