Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
821 views
in Technique[技术] by (71.8m points)

data structures - is there union and intersect Haskell Prelude implementation?

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]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...