Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.