Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
- public abstract class BinaryExpression extends BaseExpression {
- protected Expression exp1;
- protected Expression exp2;
- public BinaryExpression(Expression exp1, Expression exp2) {
- this.exp1 = exp1;
- this.exp2 = exp2;
- }
- public String toString() {
- return makeExpression(this.getPrefix(), this.exp1.toString(), this.exp2.toString(), this.getOperator());
- }
- public Expression assign(String var, Expression expression) {
- Expression returnExp1 = this.exp1;
- Expression returnExp2 = this.exp2;
- if (this.exp1.getVariables().contains(var)) {
- returnExp1 = expression.assign(var, expression);
- }
- if (this.exp2.getVariables().contains(var)) {
- returnExp2 = expression.assign(var, expression);
- }
- return this.newExpressionInstance(returnExp1, returnExp2);
- }
- public List<String> getVariables() {
- List<String> returnArray = new ArrayList<String>();
- List<String> exp2List = exp2.getVariables();
- returnArray.addAll(exp1.getVariables());
- returnArray.removeAll(exp2List);
- returnArray.addAll(exp2List);
- return returnArray;
- }
- public double evaluate(Map<String, Double> assignment) throws Exception {
- return this.doOperation(this.exp1.evaluate(assignment), this.exp2.evaluate(assignment));
- }
- public double evaluate() throws Exception {
- return this.doOperation(this.exp1.evaluate(), this.exp2.evaluate());
- }
- protected abstract double doOperation(double num1, double num2);
- protected abstract Expression newExpressionInstance(Expression exp1, Expression exp2);
- protected abstract String getOperator();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement