I have a tree represented as a nested vector. I want to have a generalization of indexed
for trees, showing the index of each node like this,
(visit 42); => [0 42]
(visit [6 7]); => [0
; [[0 6]
; [1 7]]]
The naive implementation would use clojure.zip directly (as already asked here)
(defn visit [tree]
(loop [loc (vector-zip tree)]
(if (end? loc)
(root loc)
(recur
(next (edit loc #(conj
[(count (lefts loc))]
%)))))))
But recurring with clojure.zip/next
performs a preorder traversal, resulting in an infinite loop in this case (unvisited nodes get conj
ed into a [:found]
vector infinitely). Another approach would be using clojure.walk/postwalk
, but it doesn't provide structural information, such as index.
How would you implement this? Is there a postorder-next
for zip that would solve it right away?