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

Environments and closures

Frames, name lookup, nested functions, and closures that capture the variables around them, drawn as CS61A-style environment diagrams.

CS61A
Environments · Composing Programs 1.6
Swift book
Closures

Last lesson, makeAdder(3) returned a closure that still knew n was 3 long after makeAdder had finished. To explain why, CS61A uses environment diagrams: a picture of which names are bound to which values, and where Swift looks when it meets a name.

Frames and environments

A frame is a table of bindings from names to values. The global frame holds everything bound at the top level of the program. Each call to a function creates a new local frame for its parameters and local names.

An environment is a sequence of frames. To look up a name, Swift checks the innermost frame first, then the frame it was defined in, and so on out to the global frame. The first binding found wins.

let x = 10

func f() -> Int {
    let x = 20
    return x
}

print(f(), x)   // 20 10

Here is the diagram at the moment f returns:

Global frame
  x │ 10
  f │ func f()  [parent = Global]

f  [parent = Global]
  x      │ 20
  Return │ 20

Inside f, the local x shadows the global one: lookup stops at the first frame that has the name. The global x is never changed.

What would Swift print?

let n = 1
func g(_ n: Int) -> Int {
    return n * 10
}
print(g(5), n)

Type Error if running it would crash. For several lines of output, put each on its own line.

Show answer and explanation

Answer50 1

The call g(5) creates a frame where the parameter n is 5, which shadows the global n. The body returns 50. The global n is still 1.

Drawing a diagram, step by step

CS61A draws diagrams by following a few rules, one line of code at a time. They work for Swift unchanged:

  1. A binding (let, var, or assignment) writes a name and its value in the current frame. A new let or var in an inner frame creates a new binding there, even if an outer frame has the same name.
  2. A function definition binds the function’s name to a function value, and records the function’s parent: the frame it was defined in.
  3. A call creates a new frame whose parent is the function’s parent (not the caller’s frame), binds the parameters to the argument values, and runs the body there.
  4. A return records the return value in the frame, and execution continues where the call was made.

Rule 3 is the one that surprises people. Where a function was defined decides what it can see; where it is called does not matter.

What would Swift print?

let x = 1
func f() -> Int {
    return x
}
func g() -> Int {
    let x = 2
    return f()
}
print(g())

Type Error if running it would crash. For several lines of output, put each on its own line.

Show answer and explanation

Answer1

g binds its own x to 2 and calls f. But f’s parent is the global frame, where it was defined, so the x it finds is the global one, 1.

Nested functions

A function can be defined inside another function. The inner function’s parent frame is the frame of the call that defined it, so it can use the outer function’s names:

func sumOfShifts(_ n: Int) -> Int {
    func shifted(_ k: Int) -> Int {
        k + n       // n comes from sumOfShifts's frame
    }
    return shifted(1) + shifted(2)
}
print(sumOfShifts(10))   // 23

This is lexical scoping: what a name means depends on where the code is written, not on who calls it.

Closures capture

When a closure is returned from a function, the frame it was defined in does not disappear. The closure captures the names it uses and keeps them alive:

func makeCounter() -> () -> Int {
    var count = 0
    return {
        count += 1
        return count
    }
}

let a = makeCounter()
print(a(), a(), a())   // 1 2 3

In diagram form, after the first call to a:

Global frame
  makeCounter │ func makeCounter()  [parent = Global]
  a           │ closure  [parent = f1]

f1: makeCounter  [parent = Global]
  count  │ 1          ← kept alive because the closure captured it
  Return │ closure

Each call to makeCounter makes a new frame, so each counter gets its own count.

What would Swift print?

func makeCounter() -> () -> Int {
    var count = 0
    return {
        count += 1
        return count
    }
}
let a = makeCounter()
let b = makeCounter()
print(a(), a(), b())

Type Error if running it would crash. For several lines of output, put each on its own line.

Show answer and explanation

Answer1 2 1

a and b come from two different calls, so they capture two different count variables. a counts to 2 while b starts again at 1.

Closures are reference types. Binding a closure to a second name does not copy its captured state; both names refer to the same closure.

What would Swift print?

func makeCounter() -> () -> Int {
    var count = 0
    return {
        count += 1
        return count
    }
}
let a = makeCounter()
_ = a()
let alsoA = a
print(alsoA(), a())

Type Error if running it would crash. For several lines of output, put each on its own line.

Show answer and explanation

Answer2 3

a has already counted to 1. alsoA is the same closure, so calling it gives 2, and calling a afterward gives 3.

Capturing a variable, not a value

A closure captures the variable itself, so it sees later changes. To capture the value at the moment the closure is created, list the name in a capture list in square brackets:

What would Swift print?

var x = 1
let live = { print("live", x) }
let frozen = { [x] in print("frozen", x) }
x = 2
live()
frozen()

Type Error if running it would crash. For several lines of output, put each on its own line.

Show answer and explanation

Answerlive 2\nfrozen 1

live reads x when it runs, after x has become 2. frozen copied the value of x into its capture list when it was created, when x was still 1.

Changing a captured variable

Assigning to a captured variable changes the variable itself, wherever it lives. Declaring a new variable with the same name inside the closure does not; it creates a new binding that shadows the outer one:

var total = 0
let addChanges = { (amount: Int) in total += amount }       // changes the outer total
let addShadows = { (amount: Int) in var total = 0; total += amount }   // its own total

addChanges(5)
addShadows(5)
print(total)   // 5

Python needs a nonlocal declaration to change a variable from an enclosing function; in Swift, capturing is automatic and assigning just works. The flip side is that it is easy to change shared state without meaning to, which is one reason Swift asks for @escaping and capture lists.

Put the lines in order

Put the lines in order so the program prints 5 15 12.

  1. func makeAccumulator() -> (Int) -> Int {
  2. var total = 0
  3. let deposit = makeAccumulator()
  4. return { amount in
  5. }
  6. total += amount
  7. print(deposit(5), deposit(10), deposit(-3))
  8. return total
  9. }

Show the correct program
func makeAccumulator() -> (Int) -> Int {
    var total = 0
    return { amount in
        total += amount
        return total
    }
}
let deposit = makeAccumulator()
print(deposit(5), deposit(10), deposit(-3))

Lab 4: Environments

Q0: What would Swift print?

What would Swift print?

var count = 0
func bump() -> Int {
    count += 1
    return count
}
let first = bump()
let second = bump()
print(first, second, count)

Type Error if running it would crash. For several lines of output, put each on its own line.

Show answer and explanation

Answer1 2 2

bump changes the global count each time. The first call returns 1, the second 2, and count itself is 2 afterward.

What would Swift print?

func outer() -> () -> Int {
    var n = 10
    let inner = { () -> Int in
        n += 1
        return n
    }
    n = 20
    return inner
}
let f = outer()
print(f(), f())

Type Error if running it would crash. For several lines of output, put each on its own line.

Show answer and explanation

Answer21 22

The closure captures the variable n, not its value at the time the closure was written. By the time outer returns, n is 20, so the first call gives 21 and the next 22.

What would Swift print?

func makeAdder(_ n: Int) -> (Int) -> Int {
    return { x in x + n }
}
let add5 = makeAdder(5)
let n = 100
print(add5(1))

Type Error if running it would crash. For several lines of output, put each on its own line.

Show answer and explanation

Answer6

The global n is irrelevant. The closure’s parent is the frame of the call makeAdder(5), where n is 5.

Q1: Draw it

Without running the code, draw the environment diagram at the moment the program prints, and say what it prints.

func makeMultiplier(_ factor: Int) -> (Int) -> Int {
    return { x in x * factor }
}
let factor = 100
let triple = makeMultiplier(3)
print(triple(factor))
Show solution

It prints 300.

Global frame
  makeMultiplier │ func makeMultiplier(_:)  [parent = Global]
  factor         │ 100
  triple         │ closure  [parent = f1]

f1: makeMultiplier  [parent = Global]
  factor │ 3
  Return │ closure

f2: closure  [parent = f1]
  x      │ 100
  Return │ 300

The argument factor in triple(factor) is looked up in the global frame, giving 100. Inside the closure (frame f2), factor is looked up starting from the closure’s parent, frame f1, where it is 3. The same name means two different things in two places.

Q2: Curry

curry2 turns a two-argument function into a function that takes one argument and returns another one-argument function: curry2(f)(x)(y) is f(x, y).

func curry2(_ f: @escaping (Int, Int) -> Int) -> (Int) -> (Int) -> Int {
    // your code here
}
Show solution
func curry2(_ f: @escaping (Int, Int) -> Int) -> (Int) -> (Int) -> Int {
    return { x in
        return { y in f(x, y) }
    }
}

let add = curry2(+)
let addFive = add(5)
assert(addFive(3) == 8)
assert(curry2(*)(4)(5) == 20)
assert(curry2(-)(10)(3) == 7)

The inner closure uses both x from its parent closure’s frame and f from curry2’s frame. Each layer of closure adds one frame to the chain.

Q3: A Fibonacci generator

Write makeFibber(), which returns a function that returns the next Fibonacci number each time it is called: 0, 1, 1, 2, 3, 5, …

func makeFibber() -> () -> Int {
    // your code here
}
Show solution
func makeFibber() -> () -> Int {
    var current = 0
    var next = 1
    return {
        let result = current
        (current, next) = (next, current + next)
        return result
    }
}

let fibber = makeFibber()
let firstSix = (1...6).map { _ in fibber() }
assert(firstSix == [0, 1, 1, 2, 3, 5])

let another = makeFibber()
assert(another() == 0)   // a separate frame, starting over
assert(fibber() == 8)    // the first fibber continues

current and next live in the frame of the makeFibber call and are captured by the returned closure. They are the state that survives between calls.

Q4: Draw it again

Draw the environment diagram for this program, up to the moment it prints, and say what it prints.

func makeCounter(start: Int) -> () -> Int {
    var count = start
    func next() -> Int {
        count += 1
        return count
    }
    return next
}
let c1 = makeCounter(start: 10)
let c2 = makeCounter(start: 0)
_ = c1()
print(c1(), c2())
Show solution

It prints 12 1.

Global frame
  makeCounter │ func makeCounter(start:)  [parent = Global]
  c1          │ func next()  [parent = f1]
  c2          │ func next()  [parent = f2]

f1: makeCounter  [parent = Global]
  start  │ 10
  count  │ 12
  next   │ func next()  [parent = f1]
  Return │ func next()

f2: makeCounter  [parent = Global]
  start  │ 0
  count  │ 1
  next   │ func next()  [parent = f2]
  Return │ func next()

The frames for the three calls to next (two through c1, one through c2) are omitted; each has parent f1 or f2, and changes that frame’s count. A named nested function captures exactly like a closure expression.

Q5: A withdrawal function

CS61A’s classic: write makeWithdraw(_:), which returns a function that withdraws from a balance it keeps track of. It returns the new balance as a string, or "Insufficient funds" without changing anything.

func makeWithdraw(_ balance: Int) -> (Int) -> String {
    // your code here
}
Show solution
func makeWithdraw(_ balance: Int) -> (Int) -> String {
    var balance = balance
    return { amount in
        if amount > balance {
            return "Insufficient funds"
        }
        balance -= amount
        return String(balance)
    }
}

let withdraw = makeWithdraw(100)
assert(withdraw(25) == "75")
assert(withdraw(25) == "50")
assert(withdraw(60) == "Insufficient funds")
assert(withdraw(50) == "0")

let another = makeWithdraw(10)
assert(another(5) == "5")   // separate balance

var balance = balance makes a changeable copy of the parameter in makeWithdraw’s frame; the returned closure captures and updates it.

Q6 (optional): Password protected

Write makeProtectedWithdraw(balance:password:). The returned function takes an amount and a password attempt. A wrong password returns "Incorrect password" and is remembered; after three wrong attempts the account is frozen, and every call returns "Frozen. Attempts: " followed by the array of wrong attempts.

Show solution
func makeProtectedWithdraw(balance: Int, password: String) -> (Int, String) -> String {
    var balance = balance
    var wrongAttempts: [String] = []
    return { amount, attempt in
        if wrongAttempts.count == 3 {
            return "Frozen. Attempts: \(wrongAttempts)"
        }
        if attempt != password {
            wrongAttempts.append(attempt)
            return "Incorrect password"
        }
        if amount > balance {
            return "Insufficient funds"
        }
        balance -= amount
        return String(balance)
    }
}

let withdraw = makeProtectedWithdraw(balance: 100, password: "hax0r")
assert(withdraw(25, "hax0r") == "75")
assert(withdraw(90, "hax0r") == "Insufficient funds")
assert(withdraw(25, "hwat") == "Incorrect password")
assert(withdraw(25, "hax0r") == "50")   // a right password still works
assert(withdraw(75, "a") == "Incorrect password")
assert(withdraw(10, "hax0r") == "40")
assert(withdraw(20, "n00b") == "Incorrect password")
assert(withdraw(10, "hax0r") == "Frozen. Attempts: [\"hwat\", \"a\", \"n00b\"]")

Two captured variables make up the account’s state. Each has a single place where it changes, which keeps the rules easy to check.

What’s next

Next lesson: using everything so far to design functions well, with generalization, documentation, and tests.