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

IntLists and SLLists

From a naked recursive list to a real list type: IntList with recursion and iteration, destructive and non-destructive operations, SLList with a private nested node class, cached size, sentinel nodes, invariants, and generics.

CS61B
Recursion, IntLists · SLLists, Nested Classes, Sentinel Nodes · Textbook Ch. 3, Ch. 5

Swift’s Array works so well that it is easy to forget it is a data structure someone had to build. This lesson and the next five build lists yourself, the way CS61B does, starting from the simplest possible design and fixing its problems one at a time. Each fix introduces an idea that the rest of the course uses constantly.

IntList: the naked recursive list

Lesson 12 wrote a linked list as an indirect enum, a value. CS61B starts from the same shape as a class: an item and a reference to the rest.

final class IntList {
    var first: Int
    var rest: IntList?

    init(_ first: Int, _ rest: IntList?) {
        self.first = first
        self.rest = rest
    }

    /// The number of items, recursively.
    func size() -> Int {
        1 + (rest?.size() ?? 0)
    }

    /// The number of items, with a loop.
    func iterativeSize() -> Int {
        var count = 0
        var current: IntList? = self
        while let node = current {
            count += 1
            current = node.rest
        }
        return count
    }

    /// The item at `index`, counting from 0.
    func get(_ index: Int) -> Int {
        index == 0 ? first : rest!.get(index - 1)
    }
}

let list = IntList(5, IntList(10, IntList(15, nil)))
print(list.size(), list.iterativeSize(), list.get(2))   // 3 3 15

Because the list is a class, it can be changed after it is built: list.rest!.first = 20 changes the second item for everyone who can reach that node.

size() reads beautifully, but each recursive call takes a frame on the call stack. For a list of 100,000 items, a debug build runs out of stack and crashes; optimized builds survive a little longer, and then crash too. iterativeSize() uses the same small amount of memory for any length. For linked structures that may grow long, prefer loops; keep recursion for trees, whose depth grows much more slowly than their size.

Destructive and non-destructive

A function that transforms a list can build a new one, or change the one it was given. CS61B’s pair of examples adds a number to every item:

final class IntList {
    var first: Int
    var rest: IntList?
    init(_ first: Int, _ rest: IntList?) {
        self.first = first
        self.rest = rest
    }
}

/// A new list; the original is unchanged.
func incrList(_ list: IntList?, _ x: Int) -> IntList? {
    guard let list else { return nil }
    return IntList(list.first + x, incrList(list.rest, x))
}

/// Changes the original list, and returns it.
func dincrList(_ list: IntList?, _ x: Int) -> IntList? {
    var current = list
    while let node = current {
        node.first += x
        current = node.rest
    }
    return list
}

let numbers = IntList(1, IntList(2, nil))
let bigger = incrList(numbers, 10)!
print(numbers.first, bigger.first)   // 1 11
_ = dincrList(numbers, 100)
print(numbers.first, bigger.first)   // 101 11

The d stands for destructive. Both are useful: the destructive version allocates nothing, and the other leaves the original intact for anyone who still needs it. What matters is that a function’s name and documentation say which one it is.

What would Swift print?

final class IntList {
    var first: Int
    var rest: IntList?
    init(_ first: Int, _ rest: IntList?) {
        self.first = first
        self.rest = rest
    }
}
let a = IntList(1, IntList(2, IntList(3, nil)))
let b = IntList(0, a.rest)
b.rest!.first = 20
a.rest = nil
print(a.first, b.rest!.first, b.rest!.rest!.first)

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

Show answer and explanation

Answer1 20 3

b shares a’s second node, so setting its item to 20 is visible from both. Then a.rest = nil cuts a off after its first node, but b still points at the second node, which still points at the third. Nothing is freed while something can reach it.

SLList: hiding the nodes

IntList works, but it is awkward to use. The empty list is nil, which has no methods. Adding to the front means building a node and reassigning your variable: list = IntList(0, list). And anyone holding a node can break the list, for example by making it point back at itself.

CS61B’s answer is a second class that owns the nodes and keeps them private. Users see a list with methods; only the list sees nodes:

final class SLList {
    private final class IntNode {
        var item: Int
        var next: IntNode?
        init(_ item: Int, _ next: IntNode?) {
            self.item = item
            self.next = next
        }
    }

    private var first: IntNode?
    private(set) var size = 0

    init() {}

    init(_ item: Int) {
        first = IntNode(item, nil)
        size = 1
    }

    func addFirst(_ item: Int) {
        first = IntNode(item, first)
        size += 1
    }

    func getFirst() -> Int? {
        first?.item
    }
}

let list = SLList(15)
list.addFirst(10)
list.addFirst(5)
print(list.getFirst()!, list.size)   // 5 3

Three design decisions are worth naming:

  • IntNode is a nested type (the Swift book’s chapter on nested types), declared inside SLList and marked private. Its full name is SLList.IntNode, and no code outside the list can mention it. The list’s users cannot even tell that nodes exist, so the list is free to change how it stores items later.
  • The list caches its size. Counting nodes would take time proportional to the length; updating a stored size in every method that adds or removes takes constant time. The cost is a new obligation: every method must keep size correct.
  • private(set) lets anyone read size but only the list change it, so no user can make it wrong.

The problem with addLast

Adding at the end means walking to the last node. Written directly, it has a special case:

func addLast(_ item: Int) {
    guard var node = first else {
        first = IntNode(item, nil)      // the empty list has no last node
        size += 1
        return
    }
    while let next = node.next {
        node = next
    }
    node.next = IntNode(item, nil)
    size += 1
}

One special case looks harmless. But every method that walks the list will need its own if first == nil branch, and special cases are where bugs live: the code for the empty list runs rarely, so it is tested rarely.

Sentinel nodes

The trick is to make the list never empty at the node level. A sentinel is a node that is always there, before the first real item. Its item is never used. The first real item is sentinel.next, and an empty list is a sentinel with no next:

empty:     sentinel ──▶ nil
[5, 10]:   sentinel ──▶ [5] ──▶ [10] ──▶ nil

Now every real node has a node before it, and addLast has no special case:

final class SLList {
    private final class IntNode {
        var item: Int
        var next: IntNode?
        init(_ item: Int, _ next: IntNode?) {
            self.item = item
            self.next = next
        }
    }

    /// Always present; its item is meaningless. The first item, if any, is
    /// sentinel.next.
    private let sentinel = IntNode(-1, nil)
    private(set) var size = 0

    func addFirst(_ item: Int) {
        sentinel.next = IntNode(item, sentinel.next)
        size += 1
    }

    func addLast(_ item: Int) {
        var node = sentinel
        while let next = node.next {
            node = next
        }
        node.next = IntNode(item, nil)
        size += 1
    }

    func getFirst() -> Int? {
        sentinel.next?.item
    }

    var items: [Int] {
        var result: [Int] = []
        var node = sentinel.next
        while let current = node {
            result.append(current.item)
            node = current.next
        }
        return result
    }
}

let list = SLList()
list.addLast(10)     // no special case for the empty list
list.addFirst(5)
list.addLast(15)
print(list.items, list.size)   // [5, 10, 15] 3

sentinel is a let: the arrow to the sentinel never changes, only the sentinel’s next.

Invariants

A sentinel works because of a promise the list keeps at all times: “the sentinel exists, and sentinel.next is the first item”. A fact that is true before and after every public method is called an invariant. SLList has two:

  1. sentinel.next is the first item, or nil if the list is empty.
  2. size equals the number of nodes after the sentinel.

Invariants are how you reason about a data structure: to check a method, you may assume the invariants hold when it starts, and you must make sure they hold when it ends. They are also exactly what a test should check. Lesson 21’s assert is a good way to write them into the code itself while you develop.

A list of anything

SLList only holds Ints. Lesson 16’s generics fix that: make the list generic over its Element, and the nested node uses the same parameter. The sentinel needs an item, but there is no value of an arbitrary type to put in it, so the node’s item is optional, and only the sentinel’s is nil:

final class SLList<Element> {
    private final class Node {
        var item: Element?          // nil only for the sentinel
        var next: Node?
        init(_ item: Element?, _ next: Node?) {
            self.item = item
            self.next = next
        }
    }

    private let sentinel = Node(nil, nil)
    private(set) var size = 0

    func addFirst(_ item: Element) {
        sentinel.next = Node(item, sentinel.next)
        size += 1
    }

    var first: Element? {
        sentinel.next?.item
    }
}

let names = SLList<String>()
names.addFirst("Ada")
names.addFirst("Alan")
print(names.first!, names.size)   // Alan 2

Inside SLList<Element>, the nested Node can use Element directly. Each specialization, SLList<String> or SLList<Int>, gets its own node type.

Put the lines in order

Put the lines in order so the program prints 3.

  1. head.next = Node()
  2. count += 1
  3. }
  4. final class Node {
  5. }
  6. while let node = current {
  7. current = node.next
  8. head.next!.next = Node()
  9. print(count)
  10. let head = Node()
  11. var next: Node?
  12. var count = 0, current: Node? = head

Show the correct program
final class Node {
    var next: Node?
}
let head = Node()
head.next = Node()
head.next!.next = Node()
var count = 0, current: Node? = head
while let node = current {
    count += 1
    current = node.next
}
print(count)

Lab 27: Linked lists

Q0: What would Swift print?

What would Swift print?

final class IntList {
    var first: Int
    var rest: IntList?
    init(_ first: Int, _ rest: IntList?) {
        self.first = first
        self.rest = rest
    }
}
var list: IntList? = nil
for n in 1...3 {
    list = IntList(n, list)
}
print(list!.first, list!.rest!.rest!.first)

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

Show answer and explanation

Answer3 1

Each new node goes in front, so the list is built backwards: 3, 2, 1. Adding at the front of a linked list is the cheap direction.

What would Swift print?

final class Node {
    var item: Int
    var next: Node?
    init(_ item: Int, _ next: Node?) {
        self.item = item
        self.next = next
    }
}
let sentinel = Node(99, nil)
sentinel.next = Node(1, nil)
sentinel.next = Node(2, sentinel.next)
var node = sentinel.next
var seen: [Int] = []
while let current = node {
    seen.append(current.item)
    node = current.next
}
print(seen)

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

Show answer and explanation

Answer[2, 1]

The walk starts at sentinel.next, so the sentinel’s 99 is never seen. The second node was inserted between the sentinel and the first.

Q1: get, both ways

Write get(_:) for IntList iteratively, and getRecursive(_:) recursively. Both return nil for an index past the end, rather than crashing.

Show solution
final class IntList {
    var first: Int
    var rest: IntList?
    init(_ first: Int, _ rest: IntList?) {
        self.first = first
        self.rest = rest
    }

    func get(_ index: Int) -> Int? {
        var node: IntList? = self
        for _ in 0..<index {
            node = node?.rest
        }
        return node?.first
    }

    func getRecursive(_ index: Int) -> Int? {
        index == 0 ? first : rest?.getRecursive(index - 1)
    }
}

let list = IntList(5, IntList(10, IntList(15, nil)))
assert(list.get(0) == 5 && list.get(2) == 15 && list.get(3) == nil)
assert(list.getRecursive(1) == 10 && list.getRecursive(7) == nil)

Optional chaining does the bounds checking: once node is nil, node?.rest stays nil, and so does the result.

Q2: Squares, two ways

Write square(_:), which returns a new list of the squares, leaving the original alone, and squareDestructive(_:), which squares the items in place. Write one recursively and the other with a loop.

Show solution
final class IntList {
    var first: Int
    var rest: IntList?
    init(_ first: Int, _ rest: IntList?) {
        self.first = first
        self.rest = rest
    }
    var items: [Int] {
        var result: [Int] = []
        var node: IntList? = self
        while let current = node {
            result.append(current.first)
            node = current.rest
        }
        return result
    }
}

func square(_ list: IntList?) -> IntList? {
    guard let list else { return nil }
    return IntList(list.first * list.first, square(list.rest))
}

func squareDestructive(_ list: IntList?) {
    var node = list
    while let current = node {
        current.first *= current.first
        node = current.rest
    }
}

let original = IntList(1, IntList(2, IntList(3, nil)))
let squares = square(original)!
assert(squares.items == [1, 4, 9] && original.items == [1, 2, 3])
squareDestructive(original)
assert(original.items == [1, 4, 9])
assert(square(nil) == nil)

Q3: removeFirst

Add removeFirst() to the sentinel version of SLList: it removes and returns the first item, or returns nil when the list is empty. Keep both invariants, and check them with a test that mixes all the operations.

Show solution
final class SLList {
    private final class IntNode {
        var item: Int
        var next: IntNode?
        init(_ item: Int, _ next: IntNode?) {
            self.item = item
            self.next = next
        }
    }

    private let sentinel = IntNode(-1, nil)
    private(set) var size = 0

    func addFirst(_ item: Int) {
        sentinel.next = IntNode(item, sentinel.next)
        size += 1
    }

    func addLast(_ item: Int) {
        var node = sentinel
        while let next = node.next {
            node = next
        }
        node.next = IntNode(item, nil)
        size += 1
    }

    @discardableResult
    func removeFirst() -> Int? {
        guard let first = sentinel.next else {
            return nil
        }
        sentinel.next = first.next
        size -= 1
        return first.item
    }

    var items: [Int] {
        var result: [Int] = []
        var node = sentinel.next
        while let current = node {
            result.append(current.item)
            node = current.next
        }
        return result
    }
}

let list = SLList()
var reference: [Int] = []
for n in 1...200 {
    switch n % 3 {
    case 0:
        list.addFirst(n)
        reference.insert(n, at: 0)
    case 1:
        list.addLast(n)
        reference.append(n)
    default:
        assert(list.removeFirst() == (reference.isEmpty ? nil : reference.removeFirst()))
    }
    assert(list.items == reference && list.size == reference.count)
}

The empty case is a single guard, and it is the only one: once there is a first node, removing it is the same code whether or not it is also the last. The test compares against an array after every operation, as in Lesson 27.

Q4: Reverse in place

Add reverse() to SLList, which reverses the list by changing the nodes’ next references, without creating any new nodes. It should take time proportional to the length and a constant amount of extra memory.

Show solution
final class SLList {
    private final class IntNode {
        var item: Int
        var next: IntNode?
        init(_ item: Int, _ next: IntNode?) {
            self.item = item
            self.next = next
        }
    }

    private let sentinel = IntNode(-1, nil)
    private(set) var size = 0

    func addFirst(_ item: Int) {
        sentinel.next = IntNode(item, sentinel.next)
        size += 1
    }

    func reverse() {
        var reversed: IntNode? = nil
        var remaining = sentinel.next
        while let node = remaining {
            remaining = node.next
            node.next = reversed
            reversed = node
        }
        sentinel.next = reversed
    }

    var items: [Int] {
        var result: [Int] = []
        var node = sentinel.next
        while let current = node {
            result.append(current.item)
            node = current.next
        }
        return result
    }
}

let list = SLList()
for n in [3, 2, 1] {
    list.addFirst(n)
}
list.reverse()
assert(list.items == [3, 2, 1])
list.reverse()
assert(list.items == [1, 2, 3])
let empty = SLList()
empty.reverse()
assert(empty.items.isEmpty)

Each step moves one node from the front of remaining to the front of reversed. Saving node.next before changing it is the whole trick; doing it after loses the rest of the list. Drawing the three references on paper for a list of three is the best way to convince yourself.

Q5: insert at a position

Add insert(_:at:) to SLList, which inserts an item so that it ends up at the given index. Inserting at size adds to the end. Use a precondition for indices outside 0...size.

Show solution
final class SLList {
    private final class IntNode {
        var item: Int
        var next: IntNode?
        init(_ item: Int, _ next: IntNode?) {
            self.item = item
            self.next = next
        }
    }

    private let sentinel = IntNode(-1, nil)
    private(set) var size = 0

    func insert(_ item: Int, at index: Int) {
        precondition((0...size).contains(index), "index \(index) out of range")
        var before = sentinel
        for _ in 0..<index {
            before = before.next!
        }
        before.next = IntNode(item, before.next)
        size += 1
    }

    var items: [Int] {
        var result: [Int] = []
        var node = sentinel.next
        while let current = node {
            result.append(current.item)
            node = current.next
        }
        return result
    }
}

let list = SLList()
list.insert(10, at: 0)
list.insert(30, at: 1)
list.insert(20, at: 1)
list.insert(5, at: 0)
assert(list.items == [5, 10, 20, 30] && list.size == 4)

The loop finds the node before the position, starting from the sentinel, so inserting at 0 needs no special case. The force unwrap is safe because the precondition guarantees that there are at least index real nodes.

Q6 (optional): Skippify

A CS61B exam classic. Write skippify(_:) for IntList, which destructively changes a list so that, after its first item, it skips one item, keeps the next, skips two, keeps the next, skips three, and so on: 1 through 10 becomes 1, 3, 6, 10.

Show solution
final class IntList {
    var first: Int
    var rest: IntList?
    init(_ first: Int, _ rest: IntList?) {
        self.first = first
        self.rest = rest
    }
    static func of(_ values: Int...) -> IntList? {
        values.reversed().reduce(nil) { IntList($1, $0) }
    }
    var items: [Int] {
        var result: [Int] = []
        var node: IntList? = self
        while let current = node {
            result.append(current.first)
            node = current.rest
        }
        return result
    }
}

func skippify(_ list: IntList?) {
    var kept = list
    var skip = 1
    while let node = kept {
        var next = node.rest
        for _ in 0..<skip {
            next = next?.rest
        }
        node.rest = next
        kept = next
        skip += 1
    }
}

let a = IntList.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)!
skippify(a)
assert(a.items == [1, 3, 6, 10])

let b = IntList.of(9, 8, 7, 6, 5, 4, 3, 2)!
skippify(b)
assert(b.items == [9, 7, 4])

For each kept node, walk skip nodes past its old rest and link directly to the one after. Running off the end is harmless, since optional chaining turns every further step into nil, which also ends the loop.

What’s next

addLast still walks the whole list. Next lesson: doubly linked lists, which reach both ends instantly, and a deque built from one.