Skip to content

Instantly share code, notes, and snippets.

@lilactown
Created August 11, 2018 04:30
Show Gist options
  • Save lilactown/b5e0f6b4ac45320c63ab5a07172a5250 to your computer and use it in GitHub Desktop.
Save lilactown/b5e0f6b4ac45320c63ab5a07172a5250 to your computer and use it in GitHub Desktop.
Project a map onto a tree of keys
(defn project-paths [projection]
(loop [pr projection
paths '[]]
(let [[el next] pr]
(if (empty? pr)
paths
(if (vector? next)
(recur
(drop 2 pr)
(concat paths (map #(apply vector el %) (find-paths next))))
(recur
(rest pr)
(conj paths [el])))))))
(find-paths [:a [:b1 [:c1 [:d1 :a2]]] :b [:c :d]
'a 'b 'c])
(def m {:a {:b "foo" :c {:d "1234"}} :x "456" :y 1 :z 2})
(reduce (fn [m' p]
(assoc-in m' p (get-in m p)))
{}
(project-paths [:a [:b] :y]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment