// $Id: CountLeaves.java,v 1.1 1999/11/15 05:26:53 leavens Exp $

package lib.atomic_expression;

public class CountLeaves implements Visitor {
    public CountLeaves() {}
    public Object visitNil(Nil n) {
        return new Integer(0);
    }
    public Object visitAtom(Atom a) {
        return new Integer(1);
    }
    public Object visitExpr(Expr e) {
        return
            new Integer(((Integer)(e.getLeft().visit(this))).intValue()
                        + ((Integer)(e.getRight().visit(this))).intValue());
    }

    /** to test, execute "java lib.atomic_expression.CountLeaves" **/
    public static void main(String [] argv) {
        CountLeaves cl = new CountLeaves();
        ToString ts = new ToString();
        AtomicExpression myExp
            = new Expr(new Atom(new Double(4.0)),
                       new Expr(new Atom(new Double(2.0)), new Nil()));
        AtomicExpression bigger
            = new Expr(myExp,
                       new Expr(myExp, new Nil()));
        AtomicExpression [] tests = { 
            new Nil(),
            new Atom(new Double(3.0)),
            myExp,
            bigger
        };
        for (int i = 0; i < tests.length; i++) {
            System.out.println(tests[i].visit(ts)
                           + ".visit(" + cl + ") = "
                           + tests[i].visit(cl));
        }
    }

    public String toString() {
        return "new CountLeaves()";
    }
}
