Requirements
- Build an evaluator for expressions in the style of a Basic Calculator.
- Expand the parser and evaluator to recognize additional arithmetic, including exponentiation and grouping with parentheses.
- As a follow-up, support boolean operators such as
&&, ||, and not.
- As another extension, add bitwise operators.
- Continue the discussion by introducing declarations and comparisons, for example
x = 4, y = x + 3, and x == y.
- In the final design stage, consider function definitions and invocations, such as
x = g(4) and func g(x) { x = x + 3 }.
Assume the initial callable interface is:
evaluate(expression: string) -> Value
Here, Value may represent the numeric or boolean result supported by the current stage of the language. Function definitions and declarations may be discussed as follow-up extensions rather than fully implemented in the initial version.
Examples
Example 1
Input: 5 + 3 * 2
Output: 11
Multiplication has higher precedence than addition, so the expression is evaluated as 5 + (3 * 2).
Example 2
Input: (5 + 3) * 2
Output: 16
The parentheses force the addition to happen before multiplication.
Example 3
Input: 3^2^2
Output: 81
Exponentiation associates from right to left, so this means 3^(2^2).
Constraints
- Ignore whitespace between tokens.
- Support numeric literals, parentheses, unary operators,
+, -, *, /, and ^ in the arithmetic stage.
- Preserve the usual precedence of arithmetic operators and make exponentiation right-associative.
- Treat the boolean, bitwise, variable, and function features as ordered follow-up extensions.
- The design should leave room for malformed-input handling, nested grouping, and names that may be shadowed in inner scopes.