return new Addition(l, r);
}
private Expression simplify() {
Expression l = lhs.evaluate();
Expression r = rhs.evaluate();
if (l.equals(r)) {
return new Multiplication(Naturals.getInstance().create(2), l);
} else if (l instanceof Division && r instanceof Division) {
Division dl = (Division) l;
Division dr = (Division) r;
if (dl.rhs().equals(dr.rhs())) { // common denominator
return new Division(new Addition(dl.lhs(), dr.lhs()), dl.rhs()).evaluate();
}
} else if (l instanceof Division) { // a/b + c = (a + bc) / b
Division div = (Division) l;
return new Division(new Addition(
div.lhs(), new Multiplication(div.rhs(), r)), div.rhs()).evaluate();
} else if (l instanceof Negation) { // -a + b = b - a
if (r instanceof Negation) { // -a - b = -(a + b)
return new Negation(new Addition(((Negation) l).getChild(), ((Negation) r).getChild()));
} else { // -a + b = b - a
return new Subtraction(r, ((Negation) l).getChild()).evaluate();
}
} else if (l.getPrecedence() == Precedence.Addition || r.getPrecedence() == Precedence.Addition) {
return new Sum(l, r).evaluate();
} else if (r instanceof Negation) { // a + (-b) = a - b
return new Subtraction(l, ((Negation) r).getChild()).evaluate();
}