Created
February 27, 2014 02:10
-
-
Save mpereira/9242930 to your computer and use it in GitHub Desktop.
Finding the path of a node in a tree.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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