Google
 
Web unafbapune.blogspot.com

Monday, January 30, 2012

 

Ex 4.53 genUnion and genIntersect

Write functions genUnion and genIntersect for generalized list union and list intersection. The functions should be of type [[a]] -> [a]. Note that genIntersect is undefined on the empty list of lists.

Solution 1 - 1st attempt:
genUnion :: Eq a => [[a]] -> [a]
genUnion [] = []
genUnion (x:xs) = gu2 x xs where
gu2 :: Eq a => [a] -> [[a]] -> [a]
gu2 xs [] = xs
gu2 xs (y:ys) = gu2 (u2 xs y) ys where
u2 :: Eq a => [a] -> [a] -> [a]
u2 xs [] = xs
u2 xs (y:ys)
| elem y xs = u2 xs ys
| otherwise = u2 (xs++[y]) ys

genIntersect :: Eq a => [[a]] -> [a]
genIntersect [] = error "general intersection is undefined on the empty list of lists"
genIntersect (x:xs) = gi2 x xs where
gi2 :: Eq a => [a] -> [[a]] -> [a]
gi2 xs [] = xs
gi2 xs (y:ys) = gi2 (i2 xs y) ys where
i2 :: Eq a => [a] -> [a] -> [a]
i2 [] _ = []
i2 (x:xs) ys
| elem x ys = x : i2 xs ys
| otherwise = i2 xs ys
Solution 2 - much nicer:
genUnion' :: Eq a => [[a]] -> [a]
genUnion' [] = []
genUnion' (x:xs) = union x (genUnion' xs)

genIntersect' :: Eq a => [[a]] -> [a]
genIntersect' [] = error "general intersection is undefined on the empty list of lists"
genIntersect' [xs] = xs
genIntersect' (x:xs) = intersect x (genIntersect' xs)

Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?