Skip to content

Instantly share code, notes, and snippets.

@damionjunk
Created July 11, 2012 02:37
Show Gist options
  • Save damionjunk/3087594 to your computer and use it in GitHub Desktop.
Save damionjunk/3087594 to your computer and use it in GitHub Desktop.
Data struct manipulations for 'inverting' and 'reverting' maps.
;; for a key, return a list of values
(defn sc-values
"For a given seq of maps, returns all of the values associated with
the given key 'k'. "
[k maps]
(map (fn [x] (k x)) maps))
(defn m-inverto
"invert maps, based on entries of first map, assumes uniform.
(m-inverto [{:a 1 :b 4 :c 3} {:a 2 :b 5} {:a 3 :b 6}])
;; => {:b (4 5 6), :a (1 2 3)}
"
[maps]
(let [ks (keys (first maps))]
(reduce (fn [m v] (assoc m v (sc-values v maps))) {} ks)))
(defn m-reverto
"un-inverts maps, the opposite of what happens in m-inverto.
(m-reverto {:b (4 5 6), :a (1 2 3)})
;; => ({:a 1 :b 4} {:a 2 :b 5} {:a 3 :b 6})"
[m]
(let [qua (map (fn [x]
(let [xk (first x)
xv (second x)]
(map #(hash-map xk %) xv))) m)]
(apply (partial map (fn [& x] (into {} x))) qua)))
(comment
(m-inverto [{:a 1 :b 4 :c 3} {:a 2 :b 5} {:a 3 :b 6}])
;; => {:b (4 5 6), :a (1 2 3)}
;;
;; Do some stuff to each map seq entry
;; ...
;;
(m-reverto {:b [4 5 6] :a [1 2 3] :c [3 nil nil]})
;; => ({:a 1, :b 4} {:a 2, :b 5} {:a 3, :b 6})
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment