Advertisement
gertsog

Multiset - Clojure

Dec 11th, 2019
3,412
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (defn add [multiset elem] (assoc multiset elem (+ (get multiset elem 0) 1)))
  2. (defn remove [multiset elem] (case (get multiset elem 0)
  3.                                0 multiset
  4.                                1 (dissoc multiset elem 1)
  5.                                (assoc multiset elem (- (get multiset elem) 1))))
  6. (defn union [multiset other] (reduce
  7.                                (fn [m k]
  8.                                  (assoc m k (+ (get m k 0) (get other k))))
  9.                                multiset (keys other)))
  10. (defn intersect [multiset other] (reduce
  11.                                    (fn [m k] (if (contains? multiset k) (assoc m k (min (get multiset k) (get other k)))))
  12.                                    {} (keys other)))
  13. (defn toString [multiset] (str "Bag[" (subs (reduce
  14.                                               (fn [s k] (str s ", " k ":" (get multiset k)))
  15.                                               "" (keys multiset)) 2) "]"))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement