Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traversing, iterating, visiting trees in Clojure

Tags:

clojure

Say I have a Clojure tree as defined below

(def eval-logic
  '(:OR
     (:METHOD "methodName1" ["a1" "a2" "a3"])
     (:METHOD "methodName2" ["b1" "b2" "b3"])
     :AND
       (:METHOD "methodName3" [])
       (:METHOD "methodName4" ["d1"])
     ))

I.e. the tree represents a boolean expression where nodes like :OR and :AND represent boolean operators and the leaves of the tree are method calls. The tree is not to be evaluated, only to be traversed to generate code that performs the actual evaluation at runtime. How should I go about traversing the tree, visiting different kinds of nodes, asking for a node's father, children, siblings, etc.? Are there any pointers or libraries to look into ?

The tree cannot be too deeply nested so tail-recursion is not a concern. Feel free to propose some other data-structure that might perhaps be more amenable to traversing.

I am particularly interested for depth-first traversals as this is the order that code will have to generated to ensure functions are defined before they are used. Also, the tree is given and won't change so I'm not interested in things like adding or removing children

like image 820
Marcus Junius Brutus Avatar asked Feb 13 '13 13:02

Marcus Junius Brutus


1 Answers

To move around trees at will see clojure.zip. For simple walks, see clojure.walk and tree-seq. There is an IBM article on the subject at Tree visitors in Clojure.

like image 129
A. Webb Avatar answered Nov 18 '22 04:11

A. Webb