001package visitor.expr;
002import enumeration.Op;
003
004public class Main {
005        public static void main (String[] args) {
006                Expr one = new Const(1);
007                Expr onePtwo = new BinOp (new Const(1), Op.ADD, new Const(2));
008                Expr threeMfour = new BinOp (new Const(3), Op.MUL, new Const(4));
009                Expr m = new BinOp (onePtwo, Op.SUB, threeMfour);
010                Expr n = new BinOp (m, Op.DIV, new Const(5));
011
012                System.out.println (n.accept(new PostorderToString()));
013                System.out.println ("Value: " + n.accept(new Eval()));
014        }
015}
016
017class Eval implements ExprVisitor<Integer> {
018        public Integer visitConst(int c) {
019                return c;
020        }
021        public Integer visitBinOp(Expr l, Op op, Expr r) {
022                return op.eval(l.accept(this), r.accept(this));
023        }
024}
025
026class PostorderToString implements ExprVisitor<StringBuilder> {
027        StringBuilder b = new StringBuilder();
028        public StringBuilder visitConst(int c) {
029                b.append (c + " ");
030                return b;
031        }
032        public StringBuilder visitBinOp(Expr l, Op op, Expr r) {
033                l.accept(this); r.accept(this); b.append (op + " ");
034                return b;
035        }
036}
037
038class PreOrderToString implements ExprVisitor<StringBuilder> {
039        StringBuilder b = new StringBuilder();
040        public StringBuilder visitConst(int c) {
041                b.append (c + " ");
042                return b;
043        }
044        public StringBuilder visitBinOp(Expr l, Op op, Expr r) {
045                b.append (op + " "); l.accept(this); r.accept(this);
046                return b;
047        }
048}
049
050class InOrderToString implements ExprVisitor<StringBuilder> {
051        StringBuilder b = new StringBuilder();
052        public StringBuilder visitConst(int c) {
053                b.append (c + " ");
054                return b;
055        }
056        public StringBuilder visitBinOp(Expr l, Op op, Expr r) {
057                l.accept(this); b.append (op + " "); r.accept(this);
058                return b;
059        }
060}