Parse and calculate numbers from strings like 2 * (12.4 / (7 + -2)), or multi-line inputs that separated by semicolons like x = 2; y = 5.25; z = x * (3 + -y); z.
Based on Pratt parsing and jdvillal/parser.
+-*/**(and)
-.25 + 2-1 + -2 * -3-5 * (2 + -.3)2 * (12.4 / (7 + -2))-34 * (2 + -.23)4 * (272 + 6) - 324 / 82 ** 10x = 2; y = 5.25; z = x * (3 + -y); zx = 1.6; y = .25; -((2.5 * x) ** 6) ** y / .5 ** 3
The calculator processes an input in three stages:
- Lex: splits the input string into tokens.
- Parse: builds an
ExpressionAST (Abstract Syntax Tree) from tokens with binding power of each operator. - Evaluate: traverses the AST to compute the final result.
Example
-
Input
-16 ** (.25 + (7 - -2) / 4) -
Input -> Lex -> Tokens
["-", "16", "**", "(", ".25", "+", "(", "7", "-", "-", "2", ")", "/", "4", ")"] -
Tokens -> Parse -> Expression (binding powers:
**>-negative sign,/>+and-)(- 0 (** 16 (+ 0.25 (/ (- 7 (- 0 2)) 4)))) -
Evaluate -> result
-1024
go mod tidygo test -v ./...go run .DEBUG=1 go run .After starting the calculator, you can type expressions directly into the interactive terminal, assign variables, or use built-in commands.
For example:
Enter an expression (or 'exit' to quit):
>>> 2 * (12.4 / (7 + -2))
4.96
>>> x = 10
>>> x * 3
30
Input help to see a list of available commands, supported operators, and syntax information.