How to Specify an algorithm on a predefined recursive type
without change any classes that defined this type.
interface Tree {}
class Leaf implements Tree {
Leaf(int value) {
this.value=value;
}
int value;
}
class Node implements Tree {
Node(Tree left,Tree right) {
this.left=left;
this.right=right;
}
Tree left,right;
}
public class Main extends PatternMatcher
{
public int sum(Node node)
{ return sum(node.left)+sum(node.right); }
public int sum(Leaf leaf)
{ return leaf.value; }
public int sum(Tree tree)
{ return ((Integer)match("sum",tree)).intValue(); }
public static void main(String[] args) {
Tree tree=new Node(new Node(new Leaf(1),new Leaf(3)),new Leaf(7));
System.out.println("sum "+new Main().sum(tree));
}
}