Nuthatch

Tree-Walking for Peeps

Example: ToString

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package nuthatch.examples;

import static nuthatch.library.JoinPoints.down;
import static nuthatch.library.JoinPoints.leaf;
import static nuthatch.library.JoinPoints.up;
import nuthatch.library.BaseWalk;
import nuthatch.library.Walk;
import nuthatch.walker.impl.SimpleWalker;

public class ToString {
  public static void main(String[] args) {
      // Walk which outputs the tree in a term-like representation. The result are accumulated in the
      // stringbuffer 's'.
      final StringBuffer s = new StringBuffer();
      Walk<SimpleWalker<String, String>> toTerm = new BaseWalk<SimpleWalker<String, String>>() {
          @Override
          public int step(SimpleWalker<String, String> w) {
              if(leaf(w)) { // we're at a leaf, print data value
                  s.append(w.getData().toString());
              }
              else if(down(w)) { // first time we see this node, print constructor name
                  s.append(w.getName() + "(");
              }
              else if(up(w)) { // just finished with children, close parenthesis
                  s.append(")");
              }
              else { // coming up from a child (not the last), insert a comma
                  s.append(", ");
              }

              return NEXT;
          }
      };

      // instantiate walker with an example tree and the above step function
      SimpleWalker<String, String> toTermWalker = new SimpleWalker<String, String>(ExampleTree.TREE.makeCursor(), toTerm);
      // run it
      toTermWalker.start();
      // print the contents of S
      System.out.println(s.toString());
  }
}