Tutorial outline

Unit 1

  1. 01Getting started
  2. 02Names and functions
  3. 03Control
  4. 04Higher-order functions
  5. 05Environments and closures
  6. 06Functional abstraction
  7. 07Recursion
  8. 08Tree recursion
  1. D0Getting started
  2. D1Control and environment diagrams
  3. HW1Functions and control
  4. D2Higher-order functions
  5. HW2Higher-order functions
  6. P1Hog
  7. D3Recursion
  8. D4Tree recursion
  9. HW3Recursion

Unit 2

  1. 09Sequences
  2. 10Dictionaries, sets, and tuples
  3. 11Optionals
  4. 12Structures and enumerations
  5. 13Linked lists and trees
  6. 14Mutation and value semantics
  7. 15Classes and inheritance
  8. 16Protocols and generics
  9. 17Iterators and lazy sequences
  10. 18Efficiency and memoization
  1. HW4Sequences and containers
  2. P2Cats
  3. D5Trees
  4. HW5Recursive data and mutation
  5. D6Objects and classes
  6. HW6Classes and interfaces
  7. P3Ants vs. SomeBees
  8. D7Iterators and efficiency
  9. HW7Lazy sequences and efficiency

Unit 3

  1. 19Algebraic data types and pattern matching
  2. 20Writing an interpreter
  3. 21Error handling
  4. 22Concurrency with async and await
  5. 23Testing
  6. 24Building a Swift package
  1. D8Algebraic data types
  2. HW8Pattern matching
  3. D9Interpreters
  4. HW9Interpreters and errors
  5. P4Scheme
  6. D10Concurrency
  7. D11Testing
  8. HW10Concurrency and testing

Unit 4

  1. 25References, identity, and memory
  2. 26Drawing with SwiftUI
  3. 27Testing data structures
  4. 28IntLists and SLLists
  5. 29Doubly linked lists and deques
  6. 30Arrays from scratch
  7. 31Interface and implementation inheritance
  8. 32Iteration, equality, and ordering
  9. 33Copy-on-write collections
  1. D12Swift review
  2. D13References, classes, and arrays
  3. HW11Swift warm-up
  4. P5Particle Simulator
  5. D14IntLists and SLLists
  6. HW12IntLists
  7. P6LinkedListDeque
  8. D15DLLists, default implementations, and array lists
  9. P7ArrayDeque
  10. D16Comparables and iterators
  11. HW13Review I

Unit 5

  1. 34Asymptotic analysis
  2. 35Disjoint sets
  3. 36Analyzing recursion
  4. 37Amortized analysis and the limits of big O
  5. 38Sets, maps, and binary search trees
  6. 39B-trees
  7. 40Left-leaning red-black trees
  8. 41Heaps and priority queues
  1. D17Asymptotics and disjoint sets
  2. P8Percolation
  3. D18Asymptotics II
  4. HW14Asymptotic analysis
  5. D19BSTs, B-trees, and LLRBs
  6. HW15BSTMap

Unit 6

  1. 42Data-driven apps with SwiftUI
  2. 43Tree and graph traversals
  3. 44Graph implementations
  4. 45Shortest paths: Dijkstra and A*
  5. 46Minimum spanning trees
  6. 47DAGs, topological sort, and reductions
  1. D20Tree traversals and graphs
  2. P9NGordNet
  3. D21Shortest paths and MSTs

Unit 7

  1. 48Hash tables
  2. 49Hash functions
  3. 50Tries and prefix operations
  4. 51Software engineering: managing complexity
  5. 52Games with SwiftUI
  6. 53Designing a world
  7. 54Basic sorts
  8. 55Quicksort and selection
  9. 56The limits of sorting
  10. 57Radix sorts
  11. 58Compression and complexity
  12. 59Computing, society, and what comes next
  1. D22Hashing and tries
  2. HW16Review II
  3. D23Hashing and tries, revisited
  4. P10Build Your Own World
  5. D24Sorting
  6. HW17HashMap
  7. D25Sorting II
  8. HW18LLRB set
  9. HW19Final review

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 #t and #f, and symbols like square and +.
  • Lists are written in parentheses. A list is built from pairs: a first element and the rest, ending with the empty list (). cons, car, and cdr make 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, and let.
  • Only #f is false. 0 and () are true.
  • 'x is shorthand for (quote x): the symbol x itself, 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, and procedure. Code and data have the same representation: a Scheme program is read into Values and then evaluated. description prints a value the way Scheme writes it, and toArray() turns a Scheme list into a Swift array.
  • Procedure is 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 a lambda.
  • tokenize splits text into tokens: (, ), ', and atoms. atom turns an atom’s text into a Value.
  • evaluate is 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 with specialForm(_:), or a call.
  • apply calls built-in procedures directly and sends user-defined ones to applyLambda, which you write.
  • makeGlobalFrame defines 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 provided list function. () 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 procedure ordered? 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.