Week 6: Tutorial examples

representing arithmetic expressions

abstract class Expression {
  public abstract int eval();
}

class IntExpr : Expression {
  public int i;
  public IntExpr(int i) { this.i = i; }
  
  public override int eval() => i;
}

class OpExpr : Expression {
  public char op;
  public Expression left, right;
  public OpExpr(Expression left, char op, Expression right) {
    this.left = left; this.op = op; this.right = right;
  }
  
  public override int eval() {
    int i = left.eval(), j = right.eval();
    switch (op) {
      case '+': return i + j;
      case '-': return i - j;
      case '*': return i * j;
      case '/': return i / j;
      default: return 0;
    }
  }
}