evaluate method

  1. @override
dynamic evaluate([
  1. dynamic arg
])
override

Evaluates the expression for a given value of x.

This method returns the value of the expression when evaluated at x. If x is not provided, the method should return the general form of the expression or a representative value.

Returns:

  • A dynamic representing the evaluated value of the expression.

Implementation

@override
dynamic evaluate([dynamic arg]) {
  var operandVal = operand.evaluate(arg);

  if (!prefix && operator == '!') {
    // Handle factorial - unwrap Complex to int if possible
    if (operandVal is Complex && operandVal.isReal) {
      operandVal = operandVal.simplify();
    }
    if (operandVal is double && operandVal == operandVal.truncateToDouble()) {
      operandVal = operandVal.toInt();
    }

    if (operandVal >= 0) {
      return factorial(operandVal.toInt());
    } else {
      throw Exception(
          'Factorial is only defined for non-negative integers, got: $operandVal (${operandVal.runtimeType})');
    }
  }

  switch (operator) {
    case '-':
      if (operandVal is Matrix) return -operandVal;
      return -operandVal;
    case '+':
      return operandVal;
    case '!':
      if (prefix) {
        return !operandVal;
      } else {
        // Shouldn't reach here, as factorial is handled above
        throw Exception('Unexpected use of ! operator.');
      }
    case '~':
      if (operandVal is int) {
        return ~operandVal;
      } else {
        throw Exception('Bitwise NOT is only valid for integers.');
      }
    case '%':
      if (!prefix) {
        if (operandVal is num || operandVal is Complex) {
          return operandVal * 0.01;
        }
        // If operand is expression, return Multiply(operand, 0.01)?
        // But evaluate returns dynamic (value).
        // If operandVal is not num, we can't multiply.
        // Unless we return an Expression?
        // evaluate() usually returns num or Complex.
        throw Exception('Percentage is only valid for numbers.');
      }
      throw Exception('Percentage operator % must be a suffix.');
    default:
      throw Exception('Unknown unary operator: $operator');
  }
}