Clojure: Inverting a nested hash map
We all know and love (assoc-in a kv v)
How can we take an existing map and invert it to the assoc-in commands that would create it?
I’ve been struggling with this problem for far too long. I finally found a nice solution by Jay Fields
1 2 3 4 5 6 |
(defn flatten-keys* [a ks m] (if (map? m) (reduce into (map (fn [[k v]] (flatten-keys* a (conj ks k) v)) (seq m))) (assoc a ks m))) (defn flatten-keys [m] (flatten-keys* {} [] m)) |
May 10th, 2022 at 3:54 pm
works of art.