In [2]:
package lecture;

import java.util.HashMap;


public abstract class Expr {
    
    // expressions may have children (the subexpressions that are their inputs)
    public Expr[] children;
    
    // given an binding for the variables of the expression (in this example we are considering expressions over integer variables), we want to be able to evaluate the expression
    public abstract int eval(HashMap<String,Integer> v);
}
Out[2]:
lecture.Expr
In [3]:
package lecture;

import java.util.HashMap;

// an addition sums up the result of its left and right child expression
public class Addition extends Expr {
    
    // we are passing the two children of the addition as parameters to the constructor
    public Addition(Expr left, Expr right) {
        this.children = new Expr[2];
        this.children[0] = left;
        this.children[1] = right;
    }
    
    // to evaluate an addition we compute the value of its left and right input and then add them up
    public int eval(HashMap<String,Integer> v) {
        return children[0].eval(v) + children[1].eval(v);
    }
}
Out[3]:
lecture.Addition
In [4]:
package lecture;

import java.util.HashMap;

// variables are expression which just have a name
public class Variable extends Expr {
    
    public String name;
    
    public Variable (String name) {
        this.name = name;
    }
    
    // the result of applying a valuation to a variable is the value assigned to the variable by the valuation, e.g., for a valuation x = 10, the expression "x" evaluates to 10
    public int eval(HashMap<String, Integer> v) {
        return v.get(this.name);
    }
}
Out[4]:
lecture.Variable
In [6]:
import lecture.Addition;
import lecture.Variable;
import lecture.Expr;

import java.util.HashMap;

// we create an expression tree for (x + y) + z
Expr e = new Addition (new Addition(new Variable("x"), new Variable("y")), new Variable("z"));
// we are binding x = 10, y = 10, z = 10
HashMap<String,Integer> v = new HashMap<>();
v.put("x", 20);
v.put("y", 10);
v.put("z", 10);
// evaluating the expression e with this bindings we get (10 + 10) + 10 = 30
return e.eval(v);
Out[6]:
40