I have an ANTLR3 AST which I need to traverse using a post-order, depth-first traversal which I have implemented as roughly the following Clojure:
(defn walk-tree [^CommonTree node]
(if (zero? (.getChildCount node))
(read-string (.getText node))
(execute-node
(map-action node)
(map walk-tree (.getChildren node)))))))
I would like to convert this to tail recursion using loop…recur, but I haven’t been able to figure out how to effectively use an explicit stack to do this since I need a post-order traversal.
Instead of producing a tail recursive solution which traverses the tree and visits each node, you could produce a lazy sequence of the depth first traversal using the
tree-seqfunction and then get the text out of each object in the traversal. Lazy sequences never blow the stack because they store all the state required to produce the next item in the sequence in the heap. They are very often used instead of recursive solutions like this whereloopandrecurare more diffacult.I don’t know what your tree looks like though a typical answer would look something like this. You would need to play with the “Has Children” “list of children” functions
If tree-seq does not suit your needs there are other ways to produce a lazy sequence from a tree. Look at the zipper library next.