Implement the list
union. Duplicates, and elements of the first list, are removed from the second
list, but if the first list contains duplicates, so will the result.
ListUtil.hs
listUnion :: Eq a => [a] -> [a] -> [a] listUnion xs [] = xs listUnion xs (y:ys) | (y `elem` xs) = listUnion xs ys | otherwise = listUnion (y:xs) ys
*Main> :load ListUtil.hs [1 of 1] Compiling Main ( ListUtil.hs, interpreted ) Ok, modules loaded: Main. *Main> *Main> listUnion [2, 3, 3, 4] [3, 4, 5] [5,2,3,3,4] *Main> *Main> listUnion [2, 3, 3, 4] [3, 4, 5, 2, 3, 2] [5,2,3,3,4] *Main> *Main> listUnion [2, 3, 3, 4] [3, 4, 5, 2, 3, 2, 3,3, 10, 10, 10] [10,5,2,3,3,4] *Main> :t listUnion listUnion :: Eq a => [a] -> [a] -> [a]
As you observe above
output, list2 elements come first, list2 elements come next. In case of union
function implementation in Data.List module, result contains list1 followed by
list2. Following program gives you output just like the union function in
Data.List module.
ListUtil.hs
listUnion :: Eq a => [a] -> [a] -> [a] listUnion xs [] = xs listUnion xs (y:ys) | (y `elem` xs) = listUnion xs ys | otherwise = listUnion (xs++(y:[])) ys
*Main> :load ListUtil.hs [1 of 1] Compiling Main ( ListUtil.hs, interpreted ) Ok, modules loaded: Main. *Main> *Main> listUnion [2, 3, 3, 4] [3, 4, 5] [2,3,3,4,5] *Main> *Main> listUnion [2, 3, 3, 4] [3, 4, 5, 2, 3, 2] [2,3,3,4,5] *Main> *Main> listUnion [2, 3, 3, 4] [3, 4, 5, 2, 3, 2, 3,3, 10, 10, 10] [2,3,3,4,5,10] *Main>
No comments:
Post a Comment