patternMinor
List union implementation
Viewed 0 times
listunionimplementation
Problem
I'm trying to implement
This code works, but it strikes me as verbose.
How can I make my
Revision here
union from the standard Data.List library. I know it's reinventing the wheel, but reimplementing functions is how I learn things. Any feedback at all would be helpful!union' :: (Eq a) => [a] -> [a] -> [a]
union' [] _ = []
union' _ [] = []
union' xs ys = nub' $ xs ++ ys where
nub' [] = []
nub' (x:xs)
| not $ x `elem` xs = x : nub' xs
| otherwise = nub' xsThis code works, but it strikes me as verbose.
union is the opposite of intersect, which does not require a helper where statement:intersect' :: (Eq a) => [a] -> [a] -> [a]
intersect' [] _ = []
intersect' _ [] = []
intersect' (x:xs) list
| x `elem` list = x : intersect' xs list
| otherwise = intersect' xs listHow can I make my
union function resemble the elegance of my intersect function?Revision here
Solution
Your base cases are both invalid and unnecessary:
There isn't anything bad about using
The real question you should be asking is how to avoid
union' [] _ = []
union' _ [] = []There isn't anything bad about using
where, especially when you consider that union' needs no base cases. Your question is, really, whether union' should be implemented using some kind of nub or not. If you're reinventing-the-wheel as an exercise, why wouldn't you want to reimplement nub as well?The real question you should be asking is how to avoid
++.Code Snippets
union' [] _ = []
union' _ [] = []Context
StackExchange Code Review Q#121211, answer score: 3
Revisions (0)
No revisions yet.