Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Finding the path of a node in a tree.
(defn map-zip [m]
( #(or (map? %) (map? (nth % 1)))
#(seq (if (map? %) % (nth % 1)))
(fn [x children]
(if (map? x)
(into {} children)
(assoc x 1 (into {} children))))
(defn path [m value]
(loop [current-location (map-zip m)]
(let [current-node ( current-location)
current-path ( current-location)]
(if (= (last current-node) value)
(conj (into [] (rest (map first current-path)))
(first (first current-location)))
(if ( current-location)
(recur ( current-location)))))))
(path {:a 1
:b {:c 2
:d {:e 3
:f 4
:g {:h 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.