Reputation:
I have two functions that are supposed to work on two lists.
unionB :: Eq a => [a] -> [a] -> [a]
intersectB :: Eq a => [a] -> [a] -> [a]
For unionB
I have the following code that will take the union of two lists that does this without using explicit recursion.
unionB :: Eq a => [a] -> [a] -> [a]
unionB xs ys = [xs] ++ [[y] | y <- ys]
For intersectB
I have the following code that will take the intersection of two lists (take min of counts). The only issue is that I am doing this with explicit recursion. Code is below:
intersectB :: Eq a => [a] -> [a] -> [a]
intersectB (x:xs) list
| x `elem` list = x : intersectB xs list
| otherwise = intersectB xs list
Is there any way to use the structure of my intersectB
function, except without using explicit recursion? (i.e not mentioning intersectB
within its body?)
From my understanding, intersectB
should be the opposite of what unionB
does. I am assuming that intersectB
would look extremely similar to what unionB
looks like.
I can not use any imports. I understand that there is an import out there that does this already.
Thank you.
Upvotes: 1
Views: 1307
Reputation: 71065
Your first function should be
unionB :: Eq a => [a] -> [a] -> [a]
unionB xs ys = xs ++ [y | y <- ys, not (elem y xs)]
And the second, of similar form,
intersectB :: Eq a => [a] -> [a] -> [a]
intersectB xs ys = [y | y <- ys, elem y xs]
This assumes that Bag a
is the same as [a]
.
Upvotes: 2