# Our First Grammar

The first language that we’re going to write an interpreter for is “salc,” a simple calculator. We will eventually turn salc into a full-fledged calculator, but for now we’re focusing on simplicity.

This version of salc will add single-digit numbers. Like most calculators, salc will accumulate results, so something like “1 + 2 + 3” will total to 6. Unlike normal calculators, salc will only print the result when asked. Whenever salc sees the equals sign, it will print out the current total.

From this description, the inputs

``````1 + 2 =
9 + 3 =
1 + 2 + 3 =
1 + 3 = + 5 =
``````

Should display “3,” “12,” “6” and “4 9.”

The following inputs should be rejected since they’re invalid.

``````5 - 2
92 + 1
``````

The first is invalid because this version of salc only supports addition. The second is invalid because salc only accepts single digit numbers.

## A First Stab

We’ll brute force this, so rather than going over it piece by piece, I’ll give you the first implementation. Go ahead and compile it and then run it with the samples from above.

``````Sorry, but I somehow lost this code in the shuffle.
``````

Did it work as expected? Can you think of any invalid expressions that this program will accept? Any valid expressions that it won’t accept?

On my computer, the program failed to recognize that “92 + 1” was invalid. It treated that expression as “9 + 1”. It put the “9” into the accumulator then did nothing with the “2”. That’s because it was expecting an operator and it ignored all following digits until it found one.

The program also accepts “9 2 + 1”, treating that the same as “92 + 1” because it ignores all spaces.

This goes to show that it’s easy to make mistakes even in a simple application. We’ll come back to salc in a bit, but before we do that we’ll jump into more formal specifications for our language.

In the meantime, take a shot at updating the program so that it will reject “92 + 1 =”, “9 2 + 1 =” and “9 + 2 = 3 =”.