All programs / overengineered-calculatoe
overengineered-calculatoe
A lexer, parser and tree-walking interpreter for arithmetic
Run the calculator
On CodeHS, readLine pops up a prompt. Here, what you type goes to that same call, and the program runs fresh each time.
What it does
It reads one line of arithmetic, then lexes it into tokens, parses the tokens into a syntax tree, and interprets the tree to get the answer. It handles integers and decimals, + − * / ^, parentheses and unary signs.
The interesting idea
Recursive descent, with one function per precedence level. Lower-precedence functions call higher ones, so the tree comes out the right shape without any precedence table:
expression:+and−, looping left to right (left-associative)term:*and/, also a left-to-right loopunary: a leading+or−, which calls itself so--3worksexponent:^, whose right side goes back up tounary. That makes2^3^2mean2^(3^2) = 512, and lets2^-1parse.factor: a number, or a whole parenthesisedexpression
Because unary sits above exponent, -2^2 is -(2^2) = -4, the same convention mathematicians use. The lexer is a switch (true) over character tests. The parser uses the classic peek/eat pair and checks for EOF so trailing junk is a syntax error. The interpreter is a recursive evaluate(node).
Error messages are the program’s own, rude ones included. Try 1.5.2 or 7 % 2.
Original source
The file exactly as saved on CodeHS, read-only. Open the raw file.
Evidence: CodeHS history
Screenshots of CodeHS’s “My Code History” page, which logs every save with a timestamp and the reason for it (autosave, run, paste).