How to diff/substract two lists in Clojure

algorithm, clojure, set

Solution

(defn diff [s1 s2]
  (mapcat
    (fn [[x n]] (repeat n x))
    (apply merge-with - (map frequencies [s1 s2]))))

For example, given

(def L1  [1 1 1 3 3 4 4 5 5 6])
(def L2  [1     3 3   4 5 ])

then

(diff L1 L2)
;(1 1 4 5 6)

Problem

Example: ``` 1 1 1 3 3 4 4 5 5 6 L1 1 3 3 4 5 L2 1 1 4 5 6 Res ``` Constraints: - The diff/subtract is defined as the "set" of elements from L1 minus (∖) L2 - L2 is always a subset (⊆) of L1 - The elements in L1 and L2 can have duplicates - The elements are primitives (int, string) and all of the same type `(clojure.set/difference)` doesn't help here because of (3).

Original source