Kilmix
Kilmix

Reputation: 31

How to compute the symmetric difference of two lists using list comprehension?

To get the symmetric difference of two lists I think it would be a good idea to use list comprehension. But I don't know what I could do to remove the common elements of the lists and get the elements that are different.

For example

symDiff [1,2,3,4] [1,3,5]  -- should return [2,4,5].

So far I have

symDiff :: [a] -> [a] -> [a]
symDiff xs ys = 

Upvotes: 3

Views: 504

Answers (1)

user17526644
user17526644

Reputation: 66

I hope this helps, however i was unable to do it without using Eq a

symDiff :: Eq a => [a] -> [a] -> [a]
symDiff setA setB = [c | c <- setA, not $ (elem c [x | x <- setB])]
                        ++ [c | c <- setB, not $ (elem c [x | x <- setA])]

for

symDiff [1,2,3,4] [1,3,5]

will return: [2,4,5]

Upvotes: 2

Related Questions