simplify method
Possible simplifications:
- -a * b = - (a * b)
- a * -b = - (a * b)
- -a * -b = a * b
- a * 0 = 0
- 0 * a = 0
- a * 1 = a
- 1 * a = a
Implementation
@override
Expression simplify() {
Expression firstOp = first.simplify();
Expression secondOp = second.simplify();
Expression? tempResult;
bool negative = false;
if (firstOp is UnaryMinus) {
firstOp = (firstOp).exp;
negative = !negative;
}
if (secondOp is UnaryMinus) {
secondOp = (secondOp).exp;
negative = !negative;
}
if (_isNumber(firstOp, 0)) {
return firstOp; // = 0
}
if (_isNumber(firstOp, 1)) {
tempResult = secondOp;
}
if (_isNumber(secondOp, 0)) {
return secondOp; // = 0
}
if (_isNumber(secondOp, 1)) {
tempResult = firstOp;
}
// If temp result is not set, we return a multiplication
if (tempResult == null) {
tempResult = Times(firstOp, secondOp);
return negative ? -tempResult : tempResult;
}
// Otherwise we return the only constant and just check for sign before
return negative ? UnaryMinus(tempResult) : tempResult;
}