Paste number 89840: Multimaps

Paste number 89840: Multimaps
Pasted by: stuartsierra
When:9 months, 3 weeks ago
Share:Tweet this! | http://paste.lisp.org/+1XBK
Channel:#clojure
Paste contents:
Raw Source | XML | Display As
(ns #^{:doc "A multimap is a map that permits multiple values for each
  key.  In Clojure we can represent a multimap as a map with sets as
  values."}
  multimap
  (:use [clojure.set :only (union)]))

(defn add
  "Adds key-value pairs the multimap."
  ([mm k v]
     (assoc mm k (conj (get mm k #{}) v)))
  ([mm k v & kvs]
     (apply add (add mm k v) kvs)))

(defn del
  "Removes key-value pairs from the multimap."
  ([mm k v]
     (assoc mm k (disj (get mm k) v)))
  ([mm k v & kvs]
     (apply del (del mm k v) kvs)))

(defn mm-merge
  "Merges the multimaps, taking the union of values."
  [& mms]
  (apply (partial merge-with union) mms))

(comment
  (def mm (add {} :foo 1 :foo 2 :foo 3))
  ;; mm == {:foo #{1 2 3}}

  (mm-merge mm (add {} :foo 4 :bar 2))
  ;;=> {:bar #{2}, :foo #{1 2 3 4}}

  (del mm :foo 2)
  ;;=> {:foo #{1 3}}
)

This paste has no annotations.

Colorize as:
Show Line Numbers

Lisppaste pastes can be made by anyone at any time. Imagine a fearsomely comprehensive disclaimer of liability. Now fear, comprehensively.