简体   繁体   中英

Union and Intersection of Two Lists Without Explicit Recursion

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? (ie 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM