# Haskell code for Set Difference

It’s required not to use the built-in set functions to calculate the difference between the given sets. In this scenario, we need to compare the elements of the sets to find the difference. To figure out if an element of a set is present in another set, we can use the elem function. The following code solves this problem without using any set functions.

``````setDifference :: [Integer] -> [Integer] -> [Integer]
setDifference xs ys = quicksort([] ++ combine xs ys)
where combine [] _ = []
combine (c:cs) bs = if (elem c bs)
then combine cs bs
else c : combine cs bs

quicksort :: Ord a => [a] -> [a]
quicksort [] = []
quicksort(e:es) = quicksort smaller ++ [e] ++ quicksort bigger
where bigger = [b | b <- es, b>e]
smaller = [a | a <- es, a<e]``````

The output the above code looks like this

*Main> setDifference [1,2,3,4] [1,2]
[3,4]
*Main> setDifference [] [1,2]
[]
*Main> setDifference [1,2] [1,2]
[]

## Similar Posts

This site uses Akismet to reduce spam. Learn how your comment data is processed.