0

I am trying to create functions which can find the union and intersection of two multi sets in Haskell without the use of the Multiset module. I have a good understanding of basic intersections and unions in normal lists but multisets seem to throw me. So far for the intersect function I have:

setUnique :: (Eq a) => [a] -> [a]
setUnique [] = []
setUnique (x:xs)
    | elem x xs = setUnique xs
    | otherwise = x : setUnique xs

setIntersect' :: (Eq a) => [a] -> [a]
setIntersect' xs ys = setUnique (xs ++ ys)

The issue I have in the above code is that I am actually getting values that aren't a part of the intersect. eg [1,2,2,3,3,3] [1,2,2] = [3,1,2]

  • 1
    Intersection of `[1,1,2,2]` with itself would be again `[1,1,2,2]`. I don't think `setUnique` would be very useful in computing the intersection, or in calculations with multisets in general. – n. m. could be an AI Mar 09 '16 at 19:01
  • `setIntersect'` is just reducing the union of two multisets to its underlying set. – chepner Mar 09 '16 at 22:19

1 Answers1

1

You are getting all the values because

xs ++ ys

has all elements ([1,2,2,3,3,3] ++ [1,2,2] = [1,2,2,3,3,3,1,2,2])

and setUnique is just removing the extras

setUnique [1,2,2,3,3,3,1,2,2] = [3,1,2]

I think you want to use something other than (++) here (this is what you will want for Union, you will need to write something for intersect).

jamshidh
  • 12,002
  • 17
  • 31