Skip to content

Instantly share code, notes, and snippets.

@mpereira
Created February 27, 2014 02:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpereira/9242930 to your computer and use it in GitHub Desktop.
Save mpereira/9242930 to your computer and use it in GitHub Desktop.
Finding the path of a node in a tree.
(defn map-zip [m]
(clojure.zip/zipper #(or (map? %) (map? (nth % 1)))
#(seq (if (map? %) % (nth % 1)))
(fn [x children]
(if (map? x)
(into {} children)
(assoc x 1 (into {} children))))
m))
(defn path [m value]
(loop [current-location (map-zip m)]
(let [current-node (clojure.zip/node current-location)
current-path (clojure.zip/path current-location)]
(if (= (last current-node) value)
(conj (into [] (rest (map first current-path)))
(first (first current-location)))
(if (clojure.zip/end? current-location)
nil
(recur (clojure.zip/next current-location)))))))
(path {:a 1
:b {:c 2
:d {:e 3
:f 4
:g {:h 5}}}}
5)
;; => [:b :d :g :h]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment