Module 09.2: Building a Small Lisp Interpreter¶
In Module 09.1, we learned to read expressions such as:
((lambda (x) (cons x '())) 'cat)
We can explain what this means in words: define a function, supply it with the symbol cat, construct a one-element list, and return that list. But what would a computer need in order to carry out that explanation?
We have already built most of the conceptual machinery in CS 131:
- Module 4: represent programs as data, then write functions that interpret those representations.
- Module 5: use environments to give variables meaning and closures to preserve lexical scope.
- Module 6: parse source text into structured syntax.
This module brings those ideas together in Raskell, the small Racket-like language we will implement in Haskell. Our goal is to understand a complete architecture for interpreting S-expressions, not to memorize a large evaluator or implement all of its features now. The lab and homework will give you opportunities to extend it.
By the end, you should be able to:
- Distinguish source text, parsed syntax, and runtime values.
- Identify the responsibilities of Raskell's parser, evaluator, environment, and runtime representation.
- Trace a function call through closure creation, argument evaluation, environment extension, and evaluation of the body.
- Explain why
quoteand other special forms cannot follow the ordinary function-call rule. - Distinguish an interpreter primitive, a special form, and a function written in Raskell.
- Explain how a substantial program can be written as one S-expression using local bindings, including a restricted form of recursive binding.
How to use this module
Answer the Gradescope questions in Module 9.2 Completion as you encounter them. They are meant to check your reasoning about the interpreter, not to make you write its homework implementations in advance.
Which language is being shown? Code fences marked racket show Racket-like expressions that Raskell either already supports or will support after you implement the homework. Code fences marked haskell describe the Haskell implementation. The Haskell on this page is the real code from the Raskell starter you'll use in Lab 09 and HW 09.
You can still try the Racket examples in racket on the CS 131 server. Racket's REPL prints a list result as '(cat); Raskell's printer, like this page, shows it as (cat).
1. From a string to a result¶
Consider again:
((lambda (x) (cons x '())) 'cat)
A person who knows Lisp syntax can understand it almost immediately. An interpreter has to perform several distinct tasks:
These stages answer different questions.
Parsing: What structure does the text describe? The parser must recognize symbols, parentheses, literal values, and nested lists. It does not run cons or call the function.
Evaluation: What does that structured expression mean? The evaluator follows the rules of our language. Here it creates a function value, applies it, and constructs a list.
Printing: How should we display the resulting value? A list value can be displayed in S-expression notation even though it is not the original source expression.
Notice how much of the pipeline is familiar. The distinctive feature of Lisp is that a relatively uniform data structure, the S-expression, can represent a tremendous range of programs.
2. Where the interpreter lives¶
The interpreter is written in Haskell. That makes Haskell the host language and Raskell the guest language: the language whose programs we're evaluating.
You'll work with a starter project organized like this:
| File | Responsibility |
|---|---|
RaskAST.hs |
Represent parsed expressions and runtime values; display results. |
RaskParser.hs |
Turn Raskell source text into S-expressions; handle parentheses and quote notation. |
RaskEval.hs |
Give expressions meaning using evaluation rules, environments, and function application. |
Rask.hs |
Connect reading, parsing, evaluation, and printing in an interactive interface or file runner. |
ParserCombinators.hs, ParserBase.hs |
Provided. The course's parser-combinator library from Module 6, the same one you used for piq. You don't need to understand how these files are implemented. |
rask, run-tests |
Scripts that run Raskell (compiling it when needed) and run the tests. |
The lab will walk you through finding these components in the actual repository. For now, concentrate on their responsibilities rather than the details of every imported function.
The heart of the interpreter is RaskEval.hs. That's where we'll eventually extend the language with operations such as arithmetic, comparisons, and conditionals. But a useful interpreter needs a careful representation of both what a program says and what it evaluates to.
3. Syntax is not the same as a value¶
Take this expression:
(cons 'a '())
There are two different things we might want to represent.
The program before evaluation¶
The source expression is a list-shaped instruction: call cons with two arguments. One argument is a quoted symbol; the other is a quoted empty list.
We can represent its parsed structure with a datatype like:
-- From RaskAST.hs: the syntax of a program, before evaluation
data SExpr
= SSymbol String
| SNumber Integer
| SBool Bool
| SList [SExpr]
deriving (Show, Eq)
For example, parsing:
(cons 'a '())
could produce the same structure as:
(cons (quote a) (quote ()))
because 'a is shorthand for (quote a).
We could write that syntax tree using our Haskell constructors:
SList
[ SSymbol "cons"
, SList [SSymbol "quote", SSymbol "a"]
, SList [SSymbol "quote", SList []]
]
Nothing has been evaluated yet. In particular, the first item of the outer list is still the symbol cons. It hasn't been looked up or called.
The S-expression representation is deliberately uniform: a nested application is simply a nested SList. We don't need one special syntax-tree constructor for every operation we might add later.
The result after evaluation¶
When the interpreter evaluates that expression, it should produce a list value containing the symbol a:
(a)
This is not the same thing as the original program. It is the result of running that program.
For clarity, Raskell gives runtime values a different datatype, with cases for integers, Booleans, symbols, lists, closures, and primitive functions:
-- From RaskAST.hs: the things evaluating a program can produce
data Value
= VNumber Integer
| VBool Bool
| VSymbol String
| VList [Value]
| VClosure Env [String] SExpr -- defining environment, parameters, body
| VPrim String ([Value] -> Value) -- name, and what it does to its arguments
The (a) above is the value VList [VSymbol "a"]. The important separation is:
SExpr: the structure of a program before evaluation
Value: the things evaluating a program can produce
Why include closures and primitive functions as values? Because functions are values too. A program can evaluate to a function, store one in an environment, or pass one to another function.
But isn't Raskell dynamically typed?¶
Yes, Raskell is meant to behave like a small dynamically typed language. A variable might refer to a number, a list, or a function at runtime. The interpreter checks which kind of value an operation actually receives.
This does not mean our Haskell implementation is untyped. Haskell can represent several possible runtime value variants in one algebraic datatype, and its own typechecker ensures that we handle those variants consistently.
This is a concrete instance of something we have seen throughout the course: one language can represent and interpret another language as data.
Gradescope question: Syntax versus value
Submit this response on Gradescope.
Consider:
(quote (a b))
What is the concrete source text, what kind of S-expression structure does the parser produce, and what runtime value should the evaluator return? In particular, should a and b be looked up as variables? Explain why or why not.
4. The core evaluator: one case at a time¶
The evaluator receives structured syntax and an environment, which tells it what variables mean.
The evaluator in RaskEval.hs has this type:
eval :: Env -> SExpr -> Value
Here:
Envassociates names with values.SExpris the expression to interpret.Valueis the result.
Reporting errors¶
Some Raskell programs are wrong, such as (+ 'a 1) or (first '()). The interpreter doesn't need special code to catch them. Each part of it is written with patterns that describe only the inputs that make sense. For example, here is first:
primFirst :: [Value] -> Value
primFirst [VList (x : _)] = x -- exactly one argument, and it's a nonempty list
A wrong program, such as (first '()) or (first 'a), doesn't fit that pattern, so no equation matches and Haskell stops. The REPL catches that and prints it as a Raskell error, such as error: Non-exhaustive patterns in function primFirst, and then keeps running.
The evaluator's cases¶
Let's examine the evaluator's conceptual cases. These are rules of the language, not the Haskell implementations you will write in the homework.
| Expression form | What evaluation does |
|---|---|
Integer, such as 7 |
Return the corresponding integer value. |
Boolean, such as #t |
Return the corresponding Boolean value. |
Unquoted symbol, such as x |
Look up x in the environment. |
(quote e) or 'e |
Return data representing e, without evaluating e. |
(lambda (x ...) body) |
Create a closure holding the parameters, body, and defining environment. |
(f arg ...) |
Evaluate f and its ordinary arguments, then apply the resulting function value. |
There is also an important boundary case: the empty S-expression () is valid syntax and can be used as quoted data, as in '(). But unquoted () is not a normal function application with zero arguments; there is no function in operator position. Raskell reports an error for it (error: empty application: () (did you mean '()?)), rather than accidentally treating it as both an empty-list literal and an application.
Symbols have two different roles¶
Compare:
x
with:
'x
In the first expression, x is a variable. The evaluator must consult its environment to find its value. If it is not bound, that is an error.
In the second expression, quotation tells the evaluator: return the symbol x as data. No variable lookup is needed.
This distinction is easy to miss because both expressions contain the same letters. But it is an essential part of how Lisp combines code and data.
Ordinary applications evaluate their arguments¶
Suppose the environment has a function called cons. Then:
(cons 'a '())
works by evaluating the operator and both argument expressions, obtaining:
operator value: the primitive function cons
first argument: symbol a
second argument: empty list
The primitive cons then combines those values. The primitive does not need to interpret the source text 'a or '() for itself.
A particularly nice design makes primitive functions callable values, just like closures. Then the evaluator has a shared application mechanism rather than a completely separate syntax case for every built-in function.
Gradescope question: What gets evaluated?
Submit this response on Gradescope.
Compare:
(quote (first '(a b)))
and:
(first '(a b))
In which expression does the evaluator actually call first? What should the two expressions produce, and why are the results different?
5. Follow one expression all the way through¶
Let's trace the complete expression from the start of the module:
((lambda (x) (cons x '())) 'cat)
The outermost list represents a function application. Its first element is itself a lambda expression. Its second element is the argument 'cat.
Step 1: Parse the source¶
The parser builds a nested SExpr. At the outermost level it has two elements:
function expression:
(lambda (x) (cons x '()))
argument expression:
'cat
Remember: the parser only recovers structure. It has not evaluated the argument or created a closure.
Step 2: Evaluate the function expression¶
The evaluator recognizes:
(lambda (x) (cons x '()))
as a lambda expression. Instead of evaluating its body immediately, it creates a closure that remembers three things:
parameters: x
body: (cons x '())
defining environment: the environment where the lambda appeared
Why save the environment? Because the body might refer to other variables that are not among the function's parameters. As we learned in Module 5, lexical scope means those variables should be interpreted using the bindings from the function's defining environment.
Step 3: Evaluate the argument¶
The argument is:
'cat
This means:
(quote cat)
The quote rule returns the symbol value cat. It does not try to look up a variable named cat.
Step 4: Apply the closure¶
The evaluator associates the parameter x with the argument value cat.
It creates an environment for the function body by extending the saved defining environment:
saved environment
+
x -> symbol cat
=
body environment
This binding is local to this function call. It does not mutate or replace every occurrence of x in the stored body expression.
Step 5: Evaluate the body¶
The body is:
(cons x '())
The evaluator finds the primitive function cons. It looks up x, obtaining the symbol value cat. It evaluates '() to the empty-list value. It then applies cons to those two values.
The result is a list containing one symbol:
(cat)
Finally, the printer displays that value as (cat).
Notice what did not happen¶
- The lambda's body was not evaluated when the closure was created.
- The quotation
'catdid not look upcatin the environment. - We did not substitute a string of characters into the lambda body.
- The primitive
consreceived already evaluated values, not snippets of source code.
This is the payoff of treating parsing, evaluation, environments, and function values as separate components.
A small scope variation¶
Suppose we have a function that uses a variable y without taking y as a parameter:
(lambda (x) (cons y (cons x '())))
If that function is created in an environment where y is bound to the symbol dog, its closure remembers that environment. Calling it later in a different environment where y means something else should not change what y means inside the function.
That's lexical scope. It is exactly why we made the evaluator produce closures rather than bare function bodies.
Gradescope question: Where does a free variable come from?
Submit this response on Gradescope.
A closure has body:
(cons y (cons x '()))
Its parameter is x, and it was defined in an environment where y was bound to the symbol dog. Later, someone calls it with argument 'cat in an environment where y is bound to the symbol bird.
Under lexical scope, what list should the function return? Which binding of y should it use, and why?
6. Special forms: when the usual rule is wrong¶
Our function-application rule sounds simple:
Evaluate the operator, evaluate its arguments, and apply the resulting function to the resulting values.
But some expressions must make decisions before evaluating all their parts.
We met two examples in Module 09.1.
quote: do not evaluate the argument¶
(quote (cons 'a '()))
The evaluator must return data representing the list-shaped expression. It must not run cons.
If we evaluated the argument as an ordinary function call first, quotation would no longer protect it from evaluation.
if: evaluate just one branch¶
The language you will build in Homework 9 will support:
(if #t 'safe (first '()))
The intended result is the symbol safe. The unselected branch is an invalid attempt to take first of an empty list, but it must never be evaluated.
To interpret if correctly, the evaluator has to inspect the unevaluated branch expressions and choose one after evaluating the condition. That is different from a normal function receiving three already evaluated values.
cond, and, and or¶
Homework 9 will also extend the language with more control constructs:
condexamines tests in order, evaluating the corresponding result expression only for the first successful test.andstops once a false Boolean is encountered; later expressions need not be evaluated.orstops once a true Boolean is encountered; later expressions need not be evaluated.
For our course language, we'll keep the logical operators Boolean-only, even though full Racket uses broader truthiness conventions and allows non-Boolean results from some logical forms.
We are deliberately not writing the Haskell evaluator branches for if, cond, and, or or here. Implementing them is part of the homework. The conceptual principle is enough for now:
Ordinary function calls receive evaluated values. Special forms control which pieces of syntax get evaluated.
Gradescope question: Why can't we evaluate everything first?
Submit this response on Gradescope.
Imagine an interpreter that always evaluates every part of a list before checking which language construct it represents.
Explain why that strategy would give incorrect behavior for both:
(quote (first '()))
(if #t 'yes (first '()))
What information must the interpreter preserve until it knows whether it is dealing with an ordinary function call or a special form?
7. Three ways to add a language feature¶
When building a language, it's easy to assume that every new operation requires another special case in the evaluator. Fortunately, that isn't true.
There are three different places where a feature can live.
A. A primitive operation implemented in Haskell¶
Some operations are fundamental enough that the interpreter provides them directly.
For example, the eventual Raskell language will support expressions such as:
(+ 3 4)
The arithmetic operation is implemented using Haskell's numeric capabilities. The Raskell evaluator evaluates the arguments and passes their resulting values to that primitive.
The same general idea applies to the already-provided cons operation.
A primitive function is still a function value in Raskell. It's just implemented by the host language rather than by a Raskell function body.
B. A special form with its own evaluation rule¶
quote and the planned if are different. Their behavior depends on receiving some unevaluated expressions, so the evaluator recognizes their form before proceeding with ordinary function application.
Adding one of these requires more care than merely adding a primitive that consumes evaluated arguments.
C. An ordinary function written in Raskell¶
Once Raskell supports functions, lists, recursion, and a few useful primitives, we can define new operations without changing the Haskell interpreter at all.
For instance, you will eventually implement list-processing functions such as filter and reverse in Raskell itself.
That is the bigger payoff. At some point, we stop expanding the interpreter and start using it as a programming language.
| Kind of feature | Lives primarily in | Why? |
|---|---|---|
| Arithmetic primitive | Haskell implementation | Computes on already evaluated integer values. |
| Conditional special form | Evaluator's syntax-specific rules | Must control which subexpressions are evaluated. |
| User-defined list-processing function | A Raskell program | Uses operations the language already knows. |
This distinction will also help you plan your homework implementation. Before adding a feature, ask: Does it require new evaluation behavior, or could it be expressed as a function using features we already have?
Gradescope question: Where does a feature belong?
Submit this response on Gradescope.
Classify each of these as primarily an interpreter primitive, special form, or ordinary Raskell function, and give a brief reason for each:
- Integer addition:
(+ 3 4) - A conditional that evaluates only its selected branch:
(if condition yes no) - A list function written using existing Raskell functions to construct a modified list
8. One expression can be a whole program¶
So far our examples have fit on one line. But the same S-expression representation can hold a program that spans many lines.
An interactive REPL (read-eval-print loop) is useful for testing small expressions: read an expression, evaluate it, print the result, and repeat. For a larger program, you'll want to edit a .rask file and ask the supplied runner to evaluate it.
The starter provides a file runner. ./rask with no arguments starts the REPL, and ./rask --file program.rask evaluates the program in program.rask and prints its value. You won't need to paste a huge expression into the REPL.
Local bindings¶
Our eventual language will support let, which lets us name an intermediate result within a body:
(let ((message 'hello))
(cons message '()))
This is still one expression, not a sequence of global definitions. The binding of message is available inside the let body.
We already learned in Module 5 that let can be understood in terms of function application. In the homework you'll implement that feature, and we'll encourage you to reuse the evaluator machinery you already understand.
Recursive bindings¶
A recursive function needs to refer to itself. Under lexical scope, an ordinary nonrecursive let does not automatically provide that ability.
So the teaching language will also provide a restricted letrec for one recursively defined function. The general shape is:
(letrec ((f (lambda (x) ...)))
...)
This means that the function f can refer to itself inside its body. In the homework, writing letrec is an optional challenge. You can work out the recursive environment yourself, or copy a provided solution that explains how it works.
We won't implement the recursive function here. You'll need it in the culminating homework program.
Why the file can contain one big S-expression¶
Without a global define, local bindings can nest:
(let ((a ...))
(let ((b ...))
(letrec ((f (lambda (x) ...)))
...)))
This may look unusually parenthesis-heavy at first, but it has a useful property: the entire program is an expression. It has one overall structure, one evaluation, and one resulting value.
That connects us directly back to the lambda calculus, where computation consisted of expressions rather than imperative commands.
9. The small interpreter, and the larger idea¶
Our interpreter won't be a complete Racket implementation. It won't need macros, modules, advanced number systems, mutable state, or the many facilities that make Racket a practical general-purpose language.
But the essential architecture is surprisingly small:
S-expression parser
+
syntax and runtime values
+
environments and closures
+
a handful of evaluation rules
=
a usable programming language
This is the intellectual connection to the two historical readings that Module 09.1 pointed to:
- Paul Graham, The Roots of Lisp, especially its discussion of
quoteand the compactevalfunction. Graham builds an evaluator in Lisp itself; we'll use Haskell as our host language. - John McCarthy, Recursive Functions of Symbolic Expressions and Their Computation by Machine, Part I (1960), especially the sections on S-expressions and the universal evaluation mechanism. McCarthy's original Lisp differs in several ways from our language, and his notation is further from modern Racket than Graham's.
These are optional readings, not prerequisites for the lab or homework. They offer historical perspective on why a small interpreter built from simple operations is such an important idea in programming-language design.
In the lab, you'll explore the working starter, trace a program through its components, and add one small list operation. In the homework, you'll expand the language with arithmetic, conditionals, local bindings, and list processing. Finally, you'll write a substantial program in the language you've implemented.
The questions at that point will no longer be only about whether your Haskell code works. You'll also be asking whether the programming language you built is expressive enough to let you solve a real problem.
Finish Module 09.2¶
Check that you've answered all five embedded Gradescope questions:
- Syntax versus value.
- What gets evaluated?
- Where does a free variable come from?
- Why can't we evaluate everything first?
- Where does a feature belong?
Gradescope question: Time spent
Submit this response on Gradescope.
Approximately how much time did you spend on this module?
- less than 30 minutes
- 30 - 45 minutes
- 45 - 60 minutes
- 60 - 75 minutes
- 75 - 90 minutes
- more than 90 minutes
Gradescope question: Lingering questions
Submit this response on Gradescope.
What lingering questions or thoughts do you have about this module?