Scheme
Build an interpreter for a real programming language in Swift: a reader for nested lists, frames and environments, special forms, lambda with closures, and a few Scheme programs to run on it.
Scheme is CS61A’s fourth project, and this is a Swift version of it. You will write an interpreter for Scheme, a small and elegant dialect of Lisp. When you finish, it can run recursive procedures, closures, and higher-order functions, and you will have built every piece of it except the built-in arithmetic.
The project brings the whole tutorial together: Lesson 20’s reader and eval–apply loop, Lesson 19’s algebraic data types and pattern matching, Lesson 21’s errors, and Lesson 5’s environment diagrams, which become real objects you create and search.
Getting started
Download scheme.swift into a folder of its own.
swift scheme.swift test # all problems
swift scheme.swift test 7 # one problem
swift scheme.swift # a Scheme prompt, once the interpreter works
At the prompt, type Scheme expressions and see their values. An expression
can span several lines: the prompt changes to ...> until the parentheses
balance. Press Control-D to quit. You can also run a whole file:
swift scheme.swift < program.scm
The language
Scheme programs are made of expressions, and every expression has a value. Here is most of what your interpreter will understand:
scm> (+ 1 (* 2 3))
7
scm> (define (square x) (* x x))
square
scm> (square 12)
144
scm> (define (make-adder n) (lambda (x) (+ x n)))
make-adder
scm> ((make-adder 3) 4)
7
scm> (if (> 3 2) 'yes 'no)
yes
scm> (cons 1 (list 2 3))
(1 2 3)
- Atoms are numbers (whole numbers only, in this Scheme), the booleans
#tand#f, and symbols likesquareand+. - Lists are written in parentheses. A list is built from pairs: a
first element and the rest, ending with the empty list
().cons,car, andcdrmake a pair and take it apart, like Lesson 12’s linked lists. - Call expressions apply a procedure:
(square 12). - Special forms follow their own evaluation rules:
define,quote,begin,if,lambda,and,or,cond, andlet. - Only
#fis false.0and()are true. 'xis shorthand for(quote x): the symbolxitself, not its value.- Where real Scheme leaves a value unspecified, as with
(if #f 1), this interpreter returns#f.
The provided code
Read these before starting:
Value, an indirect enum, holds every kind of Scheme value:number,boolean,symbol,null(the empty list),pair, andprocedure. Code and data have the same representation: a Scheme program is read intoValues and then evaluated.descriptionprints a value the way Scheme writes it, andtoArray()turns a Scheme list into a Swift array.Procedureis a class with a name and a kind: a Swift closure for a built-in procedure, or the formal parameters, body, and defining frame of alambda.tokenizesplits text into tokens:(,),', and atoms.atomturns an atom’s text into aValue.evaluateis the heart of the interpreter, and short: values evaluate to themselves, a symbol is looked up, and a list is either a special form, found withspecialForm(_:), or a call.applycalls built-in procedures directly and sends user-defined ones toapplyLambda, which you write.makeGlobalFramedefines the built-in procedures: arithmetic, comparisons,cons,car,cdr,list,length,append,null?, and more.
Every function you write can fail, so all of them are marked throws, and
report problems with SchemeError. Each starts out throwing
notDone(n), so the tests can tell a problem you have not started from one
that is wrong.
Phase 1: Reading and calling
Problem 1: Frames
Write define and lookup in Frame. lookup searches this frame, then
its parent, and so on up to the global frame, and throws
"unknown identifier: …" if no frame binds the name. This is Lesson 5’s
environment diagram as code.
Everything else depends on this problem, including the built-in procedures, which are defined in the global frame.
Problem 2: The reader
Write Reader.read(), which reads one expression from the tokens starting at
position, and leaves position just after it:
- An atom becomes its value, using
atom. (starts a list: read expressions until the matching), and build the list with the providedlistfunction.()is.null.'followed by an expression becomes the list(quote expression).- An unexpected
), or running out of tokens inside a list, is an error.
Like Lesson 20’s parser, this is recursive descent: a list’s elements are
read by calling read again.
Problem 3: Call expressions
Write evaluateCall: evaluate the operator, evaluate each operand in order,
then pass the procedure and the argument values to apply. After this
problem, (+ 1 (* 2 3)) works.
Phase 2: Special forms
A special form receives its operands unevaluated, as a Scheme list, and
decides for itself what to evaluate. The provided function operands(_:of:count:)
turns them into an array and checks how many there are.
Problem 4: define and quote
Write defineName, for (define name value): evaluate the value in the
current frame, bind it, and return the name as a symbol. Then write
evaluateQuote, which returns its single operand without evaluating it.
Problem 5: begin and if
Write evaluateSequence, which evaluates a list of expressions in order and
returns the last value; begin uses it, and so will procedure bodies. Then
write evaluateIf. The branch that is not taken must not be evaluated: the
tests check with (if #t 1 (quotient 1 0)).
Phase 3: User-defined procedures
Problem 6: lambda
Write makeLambda, which checks that every formal parameter is a symbol and
that the body is not empty, and returns a procedure value holding the
formals, the body, and the current frame. That frame is what makes
closures work.
Problem 7: Calling a lambda
Write Frame.makeChild(formals:values:), which creates a frame whose parent
is self and binds each formal to its argument, and applyLambda, which
makes a child of the procedure’s defining frame and evaluates the body
there.
This is the rule from Lesson 5 that makes closures and lexical scope work:
the new frame’s parent is the frame where the procedure was created, not
the frame it was called from. One test defines f to return x, then calls
it from inside a procedure with its own x; with the wrong parent, f finds
the wrong one.
Problem 8: Defining procedures
(define (square x) (* x x)) is shorthand for
(define square (lambda (x) (* x x))). Write defineProcedure, using
makeLambda with the procedure’s name, so that it prints as #[square].
Phase 4: More special forms
Problem 9: and, or, and cond
and and or evaluate their operands left to right and stop as soon as the
answer is known. and returns the first false value or, if there is none,
the last value (#t with no operands). or returns the first true value, or
#f.
cond tries each clause in turn: the first whose test is true has its body
evaluated as a sequence. A clause with no body returns the test’s value, and
else is always true. If no clause is true, the value is #f.
Problem 10: let
(let ((x 1) (y 2)) body…) evaluates every value in the current frame,
then evaluates the body in a new child frame with the names bound. The values
are all computed before any name is bound, so (let ((x 10) (y x)) …) sees
the outer x.
Phase 5: Scheme programs
Problem 11: Writing Scheme
The last problem is written in Scheme, not Swift. In the schemePrograms
string, define:
(enumerate s), which returns a list of two-element lists, each holding an index (counting from 0) and the element at that index:(enumerate '(a b c))is((0 a) (1 b) (2 c)).(merge ordered? s1 s2), which merges two lists that are already sorted by the procedureordered?into one sorted list:(merge < '(1 5 7 9) '(4 8 10))is(1 4 5 7 8 9 10).
Your interpreter runs these definitions before the tests call them, so a mistake could be in your Scheme or in your Swift. Try the pieces at the prompt first.