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

Concurrency and testing

Count words across documents in parallel, share one computation among many callers with an actor, test concurrent code with properties, control time in a rate limiter’s tests, and sort in parallel.

This homework uses Lessons 22 and 23. Put everything in hw10.swift with the assert lines, and run it. Concurrent code can pass a test by luck, so the tests here check properties that must hold in every ordering of events, not just the one that happened.

Q1: Word counts in parallel

Write wordCounts(_:), which counts the words of several documents concurrently, one child task per document, and merges the per-document counts into one dictionary. Words are separated by spaces, and case does not matter.

Show solution
func count(_ document: String) -> [String: Int] {
    var counts: [String: Int] = [:]
    for word in document.lowercased().split(separator: " ") {
        counts[String(word), default: 0] += 1
    }
    return counts
}

func wordCounts(_ documents: [String]) async -> [String: Int] {
    await withTaskGroup(of: [String: Int].self) { group in
        for document in documents {
            group.addTask { count(document) }
        }
        var total: [String: Int] = [:]
        for await partial in group {
            total.merge(partial, uniquingKeysWith: +)
        }
        return total
    }
}

let counts = await wordCounts(["The cat sat", "the dog", "A cat and a dog"])
assert(counts == ["the": 2, "cat": 2, "sat": 1, "dog": 2, "a": 2, "and": 1])
let empty = await wordCounts([])
assert(empty.isEmpty)

No actor is needed: each task builds its own dictionary, and only the group’s own loop, which runs in one task, merges them. Giving each task its own data and combining at the end avoids shared mutable state entirely, which is the simplest way to be free of data races. merge(_:uniquingKeysWith:) adds the counts for words that appear in both.

Q2: Asking only once

Several parts of an app may ask for the same slow result at the same time, such as a user’s profile. Write an actor Loader whose value(for:) calls the provided load function at most once per key, even when many callers ask concurrently before the first load has finished. Store the in-progress Task for each key, and let later callers await the same task.

Show solution
actor Loader {
    private var tasks: [String: Task<Int, Never>] = [:]
    private(set) var loads = 0
    private let load: @Sendable (String) async -> Int

    init(load: @escaping @Sendable (String) async -> Int) {
        self.load = load
    }

    func value(for key: String) async -> Int {
        if let existing = tasks[key] {
            return await existing.value
        }
        loads += 1
        let task = Task { await load(key) }
        tasks[key] = task
        return await task.value
    }
}

let loader = Loader { key in
    try? await Task.sleep(for: .milliseconds(50))
    return key.count
}

let results = await withTaskGroup(of: Int.self) { group in
    for key in ["ada", "alan", "ada", "ada", "alan", "grace"] {
        group.addTask { await loader.value(for: key) }
    }
    return await group.reduce(0, +)
}
let loads = await loader.loads
assert(results == 3 + 4 + 3 + 3 + 4 + 5)
assert(loads == 3)   // one per distinct key

The important detail is where the task is stored: before the first await. The check and the store run without suspending, so the next caller for the same key is guaranteed to find the task, even though the load itself has not finished. Storing the result after awaiting it would let every concurrent caller start its own load: Discussion 10’s ticket bug in another form.

Q3: Testing a concurrent map

Lesson 22’s lab wrote concurrentMap. Test it with a property: for random arrays of 0 to 20 numbers, with a random delay for each element, concurrentMap must return exactly what map returns. Use a seeded generator so failures can be reproduced.

Show solution
struct SeededGenerator: RandomNumberGenerator {
    var state: UInt64

    mutating func next() -> UInt64 {
        state &+= 0x9E3779B97F4A7C15
        var z = state
        z = (z ^ (z >> 30)) &* 0xBF58476D1CE4E5B9
        z = (z ^ (z >> 27)) &* 0x94D049BB133111EB
        return z ^ (z >> 31)
    }
}

func concurrentMap<T: Sendable, U: Sendable>(
    _ items: [T],
    _ transform: @escaping @Sendable (T) async -> U
) async -> [U] {
    await withTaskGroup(of: (Int, U).self) { group in
        for (index, item) in items.enumerated() {
            group.addTask { (index, await transform(item)) }
        }
        var results = [U?](repeating: nil, count: items.count)
        for await (index, result) in group {
            results[index] = result
        }
        return results.map { $0! }
    }
}

var random = SeededGenerator(state: 2026)
for trial in 1...20 {
    let input = (0..<Int.random(in: 0...20, using: &random)).map { _ in
        (value: Int.random(in: -50...50, using: &random), delay: Int.random(in: 0...5, using: &random))
    }
    let expected = input.map { $0.value * $0.value }
    let actual = await concurrentMap(input) { item in
        try? await Task.sleep(for: .milliseconds(item.delay))
        return item.value * item.value
    }
    assert(actual == expected, "trial \(trial): \(input)")
}

Random delays make the tasks finish in a different order each trial, which is exactly what could break a wrong implementation, such as one that appended results as they arrived. The delays come from the seeded generator, but the actual timing still varies from run to run, so this test is not perfectly repeatable. That is normal for concurrent code, and is why the property compares against plain map instead of a fixed order of events.

Q4: A rate limiter with a fake clock

A token bucket limits how often something may happen. The bucket holds up to capacity tokens and gains perSecond tokens each second (never going over capacity). Each request takes one token, and is refused if the bucket is empty. Write TokenBucket, taking the current time, in seconds, from a function passed to its initializer, and test it with a clock you control.

Show solution
struct TokenBucket {
    let capacity: Double
    let perSecond: Double
    private let now: () -> Double
    private var tokens: Double
    private var lastRefill: Double

    init(capacity: Int, perSecond: Double, now: @escaping () -> Double) {
        self.capacity = Double(capacity)
        self.perSecond = perSecond
        self.now = now
        tokens = Double(capacity)
        lastRefill = now()
    }

    mutating func allow() -> Bool {
        let time = now()
        tokens = min(capacity, tokens + (time - lastRefill) * perSecond)
        lastRefill = time
        guard tokens >= 1 else {
            return false
        }
        tokens -= 1
        return true
    }
}

final class FakeClock {
    var time = 0.0
}

let clock = FakeClock()
var bucket = TokenBucket(capacity: 3, perSecond: 2) { clock.time }

assert([bucket.allow(), bucket.allow(), bucket.allow(), bucket.allow()] == [true, true, true, false])
clock.time = 0.5    // half a second: one new token
assert(bucket.allow() && !bucket.allow())
clock.time = 100    // a long pause refills to capacity, not beyond
assert([bucket.allow(), bucket.allow(), bucket.allow(), bucket.allow()] == [true, true, true, false])

With a real clock, testing the refill would mean sleeping, and the result would depend on how fast the computer is. The fake clock makes time a value the test sets, so the test runs instantly and gives the same answer every time. FakeClock is a class, so the closure and the test share it.

Q5 (optional): Parallel merge sort

Write parallelSort(_:), a merge sort that sorts the two halves concurrently with async let, falling back to sorted() for arrays of 1,000 elements or fewer, where starting tasks would cost more than it saves. Test it against sorted() on random arrays.

Show solution
func merge(_ a: [Int], _ b: [Int]) -> [Int] {
    var result: [Int] = []
    result.reserveCapacity(a.count + b.count)
    var i = 0
    var j = 0
    while i < a.count && j < b.count {
        if a[i] <= b[j] {
            result.append(a[i])
            i += 1
        } else {
            result.append(b[j])
            j += 1
        }
    }
    return result + a[i...] + b[j...]
}

func parallelSort(_ values: [Int]) async -> [Int] {
    guard values.count > 1000 else {
        return values.sorted()
    }
    let middle = values.count / 2
    async let left = parallelSort(Array(values[..<middle]))
    async let right = parallelSort(Array(values[middle...]))
    return await merge(left, right)
}

var generator = SystemRandomNumberGenerator()
for size in [0, 1, 999, 1001, 20_000] {
    let values = (0..<size).map { _ in Int.random(in: -1000...1000, using: &generator) }
    let sorted = await parallelSort(values)
    assert(sorted == values.sorted(), "size \(size)")
}

The sizes are chosen at the boundaries: empty, one element, just under and just over the threshold, and one large enough to split several times. Each level of recursion splits into two tasks, so a 20,000-element array ends in 32 small sorts, which the runtime spreads over as many cores as the machine has.