This simple example shows how to a walk a tree and convert it to a term
representation (such as +(5, *(+(7, 3), 4)), for example).
In the example, we carefully observe the position along the walk to
correctly parenthesize and place commas where appropriate. For a leaf, we
use its data value. If we enter a node from the parent, we use its
constructor name and add open parenthesis. Whenever we come up from a
child, we add a comma, except when we come up from the last child, where we
add the closing parenthesis.
The walk proceeds from node to node according to the default walk,
shown to the right.
The SimpleWalker carries with it a string S as state, which we may
append to (appendToS()), observe (getS()) and set (setS()).
Convert a tree to its term representation (ToString.java)download
packagenuthatch.examples;importstaticnuthatch.library.JoinPoints.down;importstaticnuthatch.library.JoinPoints.leaf;importstaticnuthatch.library.JoinPoints.up;importnuthatch.library.BaseWalk;importnuthatch.library.Walk;importnuthatch.walker.impl.SimpleWalker;publicclassToString{publicstaticvoidmain(String[]args){// Walk which outputs the tree in a term-like representation. The result are accumulated in the// stringbuffer 's'.finalStringBuffers=newStringBuffer();Walk<SimpleWalker<String,String>>toTerm=newBaseWalk<SimpleWalker<String,String>>(){@Overridepublicintstep(SimpleWalker<String,String>w){if(leaf(w)){// we're at a leaf, print data values.append(w.getData().toString());}elseif(down(w)){// first time we see this node, print constructor names.append(w.getName()+"(");}elseif(up(w)){// just finished with children, close parenthesiss.append(")");}else{// coming up from a child (not the last), insert a commas.append(", ");}returnNEXT;}};// instantiate walker with an example tree and the above step functionSimpleWalker<String,String>toTermWalker=newSimpleWalker<String,String>(ExampleTree.TREE.makeCursor(),toTerm);// run ittoTermWalker.start();// print the contents of SSystem.out.println(s.toString());}}