Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
like image 496
Fopa Léon Constantin Avatar asked May 13 '11 03:05

Fopa Léon Constantin


1 Answers

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

like image 126
C. A. McCann Avatar answered Sep 28 '22 01:09

C. A. McCann