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

Pattern matching

A robot that follows nested commands, classifying poker hands by pattern, printing expressions with the fewest parentheses, a file-system tree, run-length encoding, and merging lists by matching two at once.

This homework uses Lesson 19. Put everything in hw08.swift with the assert lines, and run it. In every problem, let the shape of the data decide the shape of the code: one case per kind of value, and a pattern wherever you would otherwise check a condition by hand.

Q1: Robot commands

A robot on a grid starts at (0, 0) facing north. It understands four commands, one of which contains other commands. Write run(_:), which returns the robot’s final position.

enum Command {
    case forward(Int)
    case left
    case right
    case repeatTimes(Int, [Command])
}

Facing north, forward(2) moves to (0, 2); facing east, it moves to (2, 0). left and right turn 90 degrees.

Show solution
enum Command {
    case forward(Int)
    case left
    case right
    case repeatTimes(Int, [Command])
}

struct Robot {
    var x = 0
    var y = 0
    var dx = 0
    var dy = 1   // facing north

    mutating func perform(_ command: Command) {
        switch command {
        case .forward(let steps):
            x += dx * steps
            y += dy * steps
        case .left:
            (dx, dy) = (-dy, dx)
        case .right:
            (dx, dy) = (dy, -dx)
        case .repeatTimes(let times, let body):
            for _ in 0..<times {
                for inner in body {
                    perform(inner)
                }
            }
        }
    }
}

func run(_ commands: [Command]) -> (Int, Int) {
    var robot = Robot()
    for command in commands {
        robot.perform(command)
    }
    return (robot.x, robot.y)
}

assert(run([.forward(2), .right, .forward(3)]) == (3, 2))
assert(run([.repeatTimes(4, [.forward(5), .left])]) == (0, 0))   // a square
assert(run([.repeatTimes(2, [.forward(1), .repeatTimes(3, [.right])])]) == (-1, 1))

Storing the direction as a vector turns turning into arithmetic: rotating (dx, dy) left gives (−dy, dx). repeatTimes holds commands, so perform calls itself on them: a recursive data type gets a recursive function. Three right turns equal one left turn, which the last test checks.

Q2: Poker hands

Write classify(_:), which names a hand of five card ranks. Count how many times each rank appears, sort the counts from largest to smallest, and switch on that array. Ignore straights and flushes.

Counts Hand
[4, 1] four of a kind
[3, 2] full house
[3, 1, 1] three of a kind
[2, 2, 1] two pair
[2, 1, 1, 1] one pair
otherwise high card
Show solution
func classify(_ ranks: [Int]) -> String {
    precondition(ranks.count == 5, "a hand has five cards")
    var counts: [Int: Int] = [:]
    for rank in ranks {
        counts[rank, default: 0] += 1
    }
    switch counts.values.sorted(by: >) {
    case [4, 1]: return "four of a kind"
    case [3, 2]: return "full house"
    case [3, 1, 1]: return "three of a kind"
    case [2, 2, 1]: return "two pair"
    case [2, 1, 1, 1]: return "one pair"
    default: return "high card"
    }
}

assert(classify([9, 9, 9, 9, 2]) == "four of a kind")
assert(classify([3, 13, 3, 13, 3]) == "full house")
assert(classify([5, 8, 5, 11, 2]) == "one pair")
assert(classify([2, 7, 7, 2, 12]) == "two pair")
assert(classify([1, 4, 6, 9, 13]) == "high card")

An array literal in a case is an expression pattern: it matches when the value equals it. Sorting the counts first means the order of the cards does not matter, which turns the whole classification into a lookup table.

Q3: Fewer parentheses

Lesson 19’s show wrapped every addition in parentheses. Write show(_:) so that it adds parentheses only where they are needed: around an addition that is an operand of a multiplication. Addition and multiplication are associative, so 1 + (2 + 3) can be written 1 + 2 + 3.

indirect enum Expr {
    case number(Int)
    case variable
    case add(Expr, Expr)
    case multiply(Expr, Expr)
}
Show solution
indirect enum Expr {
    case number(Int)
    case variable
    case add(Expr, Expr)
    case multiply(Expr, Expr)
}

func show(_ expr: Expr) -> String {
    func factor(_ e: Expr) -> String {
        if case .add = e {
            return "(\(show(e)))"
        }
        return show(e)
    }

    switch expr {
    case .number(let n): return "\(n)"
    case .variable: return "x"
    case .add(let a, let b): return "\(show(a)) + \(show(b))"
    case .multiply(let a, let b): return "\(factor(a)) * \(factor(b))"
    }
}

let x = Expr.variable
assert(show(.add(.number(1), .add(x, .number(3)))) == "1 + x + 3")
assert(show(.multiply(.add(x, .number(1)), .number(3))) == "(x + 1) * 3")
assert(show(.add(.multiply(.number(2), x), .number(1))) == "2 * x + 1")
assert(show(.multiply(.number(2), .multiply(x, x))) == "2 * x * x")

if case .add = e asks only which case e is, without binding anything. The helper factor handles the one situation that needs parentheses; every other combination prints the same with or without them.

Q4: A file system

A file system is a tree: a folder holds files and other folders. Write totalSize(_:), and largeFiles(_:over:), which returns the paths of all files larger than a limit, like "home/photos/cat.jpg", in the order they appear.

indirect enum Item {
    case file(name: String, size: Int)
    case folder(name: String, contents: [Item])
}
Show solution
indirect enum Item {
    case file(name: String, size: Int)
    case folder(name: String, contents: [Item])
}

func totalSize(_ item: Item) -> Int {
    switch item {
    case .file(_, let size):
        size
    case .folder(_, let contents):
        contents.map(totalSize).reduce(0, +)
    }
}

func largeFiles(_ item: Item, over limit: Int) -> [String] {
    switch item {
    case .file(let name, let size):
        return size > limit ? [name] : []
    case .folder(let name, let contents):
        return contents.flatMap { largeFiles($0, over: limit) }.map { "\(name)/\($0)" }
    }
}

let home = Item.folder(name: "home", contents: [
    .file(name: "notes.txt", size: 4),
    .folder(name: "photos", contents: [
        .file(name: "cat.jpg", size: 900),
        .file(name: "dog.jpg", size: 700),
    ]),
    .folder(name: "empty", contents: []),
    .file(name: "movie.mp4", size: 5000),
])

assert(totalSize(home) == 6604)
assert(largeFiles(home, over: 800) == ["home/photos/cat.jpg", "home/movie.mp4"])
assert(largeFiles(.file(name: "a", size: 1), over: 0) == ["a"])

Each folder puts its own name in front of every path its contents return, the same way Lesson 12’s allPaths put a label in front of every path from a branch.

Q5: Run-length encoding

Run-length encoding compresses repeated characters: "aaabccdddd" becomes a single a repeated 3 times, then b, then c twice, then d 4 times. Write encode(_:) and decode(_:) using this enum, and check that decoding an encoding gives back the original.

enum Run: Equatable {
    case single(Character)
    case repeated(Character, Int)
}
Show solution
enum Run: Equatable {
    case single(Character)
    case repeated(Character, Int)
}

func encode(_ text: String) -> [Run] {
    var runs: [Run] = []
    for character in text {
        switch runs.last {
        case .single(let c) where c == character:
            runs[runs.count - 1] = .repeated(c, 2)
        case .repeated(let c, let n) where c == character:
            runs[runs.count - 1] = .repeated(c, n + 1)
        default:
            runs.append(.single(character))
        }
    }
    return runs
}

func decode(_ runs: [Run]) -> String {
    var text = ""
    for run in runs {
        switch run {
        case .single(let c): text.append(c)
        case .repeated(let c, let n): text += String(repeating: c, count: n)
        }
    }
    return text
}

assert(encode("aaabccdddd") == [.repeated("a", 3), .single("b"), .repeated("c", 2), .repeated("d", 4)])
assert(encode("") == [])
for text in ["aaabccdddd", "", "abc", "zzzzzzzzzz"] {
    assert(decode(encode(text)) == text)
}

runs.last is an optional, and matching it against .single(let c) works without unwrapping first: Swift lifts enum case patterns through optionals automatically, so nil simply matches nothing but default. The round-trip check at the end is a property test from Lesson 23, in miniature.

Q6 (optional): Merging two lists

Write merge(_:_:), which merges two sorted linked lists into one sorted list, with a single switch on the pair (a, b).

indirect enum List: Equatable {
    case empty
    case node(Int, List)
}
Show solution
indirect enum List: Equatable {
    case empty
    case node(Int, List)
}

func merge(_ a: List, _ b: List) -> List {
    switch (a, b) {
    case (.empty, let rest), (let rest, .empty):
        return rest
    case let (.node(x, restA), .node(y, _)) where x <= y:
        return .node(x, merge(restA, b))
    case let (.node, .node(y, restB)):
        return .node(y, merge(a, restB))
    }
}

func list(_ values: Int...) -> List {
    values.reversed().reduce(List.empty) { .node($1, $0) }
}

assert(merge(list(1, 4, 6), list(2, 3, 7, 8)) == list(1, 2, 3, 4, 6, 7, 8))
assert(merge(list(), list(5)) == list(5))
assert(merge(list(2, 2), list(2)) == list(2, 2, 2))

The first case handles either list being empty with one pattern. After it, both are nodes, and the where clause chooses which head comes first. The compiler checks that the three cases together cover every pair. Int... makes list take any number of arguments, as an array.