Is there a standard/library function to transpose a map from key-value to 
value-keys?

I've met this task many times before, and I'm sure others have too. Here is the 
code I'm using, mildly highlighted by Google 
Groups. I used to copy-paste from Pygments.org 
<http://pygments.org/demo/506245/>, but it seems to no longer work.

(defn transpose
  "Transposes a map of the form k_i -> v_i into v_j -> #{k_j1 k_j2 ...}"
  [m]
  (reduce (fn [acc [k v]]
            (assoc acc v 
              (conj (get acc v #{}) k)))
          {} m))

(transpose {:a 1 :b 1 :c 2 :d 4 :e 2 :f 1}) ;=> {4 #{:d}, 2 #{:c :e}, 1 
#{:a :b :f}}

(defn inverse-transpose
  "Transposes back a map of the form v_i -> #{k_i1 k_12 ...} into k_j -> 
v_j"
  [m]
  (into {} (mapcat (fn [[v ks]] 
                     (map #(vector %1 %2) ks (repeat v))) 
                   m)))

(inverse-transpose (transpose {:a 1 :b 1 :c 2 :d 4 :e 2 :f 1})) ;=> {:d 4, :c 
2, :e 2, :a 1, :b 1, :f 1}

(let [m {:a 1 :b 1 :c 2 :d 4 :e 2 :f 1}]
  (= m (inverse-transpose (transpose m)))) ;=> true
 

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
--- 
You received this message because you are subscribed to the Google Groups 
"Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to clojure+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to