simplify method

  1. @override
Expression simplify()
override

Possible simplifications:

  1. -a * b = - (a * b)
  2. a * -b = - (a * b)
  3. -a * -b = a * b
  4. a * 0 = 0
  5. 0 * a = 0
  6. a * 1 = a
  7. 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;
}