Scheem Interpreter

If you don't understand interpreters, you can still write programs; you can even be a competent programmer. But you can't be a master.

Hal Abelson, in the foreword to Essentials of Programming Languages

In these exercises we'll work on defining a Scheem interpreter. Just in case you don't remember all the way back to last week, Scheem is our cut-down version of Scheme. We've got parsing covered, so we can assume that Scheem programs are represented as JavaScript lists. Atoms are just strings or numbers. We'll go through and steal a bunch of features from Scheme to make our Scheem language.

Interpreting arithmetic

What will our interpreter do? Let's start with arithmetic. Our interpreter should be able to evaluate Scheem programs like this.

Our interpreter function will be called evalScheem. It will take a fully parsed Scheem expression as input, and it will return the value the expression evaluates to. In the example above it will return 11. That's because 5+2*3=11. Look, Ma, I can do math!

Here's one way to write evalScheem that works for addition and subtraction.

Some things to notice: we use typeof to check whether the input is a single number or a list. Also, the evalScheem function recursively calls itself to evaluate the arguments to the operation. To do an addition, we evaluate the two arguments, add them, then return the sum.

Write an evalScheem function that can correctly handle multiplication and division operations along with addition and subtraction. All arithmetic operations take exactly two arguments.

1:1



Next