build-a-programming-language / lesson-25.md
Lesson 25 · Evaluation

Integer arithmetic

Now the evaluator does real math. Today you evaluate infix + - * / on integers, recursively evaluating each side first - and pin down how integer division truncates.

The goal

Evaluate the four arithmetic operators on integer operands, respecting precedence from the parser.

Start here - the target
TO DO
Scenario: Evaluating integer arithmetic
Givenarithmetic expressions over integers
Whenthe evaluator evaluates 2 + 3 * 4, then (2 + 3) * 4, then 7 / 2
Thenthe results are 14, 20, and 3
Andinteger division truncates toward zero, so 7 / 2 is 3 and not 3.5
Background

To evaluate an infix expression, first recursively evaluate both sides into objects, then combine them. When both are integers, + - * / do the obvious thing. Because the parser already resolved precedence into the tree’s shape, the evaluator does no precedence work at all - 2 + 3 * 4 is 2 + (3 * 4) in the tree, so evaluating it bottom-up gives 14 for free.

One boundary matters: this language’s numbers are integers, so division truncates - 7 / 2 is 3, not 3.5. Name that explicitly, because a learner porting this to a language with floating-point division could get 3.5 and think they were right. Floating-point numbers are a deliberate non-goal; keeping numbers integral keeps every result exactly checkable.

Make it work
func evalIntInfix(op string, l, r *Integer) Object {
switch op {
case "+": return &Integer{l.Value + r.Value}
case "-": return &Integer{l.Value - r.Value}
case "*": return &Integer{l.Value * r.Value}
case "/": return &Integer{l.Value / r.Value} // integer division
}
}
CheckpointDONE
The evaluator computes integer arithmetic, honoring the parser's precedence. Commit.