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

Algebraic data types and pattern matching

Product and sum types, enums that make illegal states unrepresentable, exhaustive switches, Swift’s full pattern language, and an expression tree simplified by matching on its shape.

CS61A
Functional Programming · Algebraic Data Types · Immutable Data
Swift book
Enumerations · Generics
Documentation
Optional · Result

CS61A’s last unit switches to a functional language to study programs built from immutable data and pattern matching. Swift has both already: you have used enums with associated values since Lesson 11, and switch since Lesson 2. This lesson puts them at the center. The goal is a style of programming in which the type describes every situation the program can be in, and the compiler checks that each one is handled.

Products and sums

A structure holds one value of each of its properties at once. A structure with two Bool properties has 2 × 2 = 4 possible values, so it is called a product type. Tuples are product types too.

An enumeration holds one of its cases. An enum with three cases, none carrying data, has 1 + 1 + 1 = 3 possible values, so it is a sum type. When cases carry associated values, each case contributes a product:

enum Suit {
    case clubs, diamonds, hearts, spades           // 4 values
}

struct Card {
    let rank: Int                                   // 13 ranks × 4 suits = 52 cards
    let suit: Suit
}

enum Payment {
    case cash                                       // 1
    case card(lastFour: Int)                        // + one for each number
    case transfer(from: String, reference: String)  // + one for each pair of strings
}

let payments: [Payment] = [.cash, .card(lastFour: 4242), .transfer(from: "Ada", reference: "rent")]
print(payments.count)   // 3

Types built by combining products and sums like this are called algebraic data types, because counting their values is algebra: × for “and”, + for “or”. The counting is not just a curiosity. It tells you how many situations your code has to handle, and whether the type allows situations that should be impossible.

Making illegal states unrepresentable

Here is a download described with a structure. It is easy to write, but count its states:

struct Download {
    var isFinished = false
    var fraction = 0.0
    var data: String? = nil
    var failure: String? = nil
}

// Nothing stops this: finished, 30% done, with both data and an error.
let nonsense = Download(isFinished: true, fraction: 0.3, data: "hello", failure: "timed out")
print(nonsense.isFinished)   // true

Every function that receives a Download has to decide what to do with combinations that make no sense. An enum lists exactly the states that can happen, and gives each one only the data that belongs to it:

enum DownloadState {
    case notStarted
    case inProgress(fraction: Double)
    case finished(data: String)
    case failed(reason: String)
}

func status(_ state: DownloadState) -> String {
    switch state {
    case .notStarted:
        "Waiting"
    case .inProgress(let fraction):
        "\(Int(fraction * 100))% done"
    case .finished(let data):
        "Got \(data.count) characters"
    case .failed(let reason):
        "Failed: \(reason)"
    }
}

print(status(.inProgress(fraction: 0.25)))   // 25% done
print(status(.failed(reason: "timed out")))  // Failed: timed out

There is no way to build a finished download without data, or a failed one without a reason. A bug that cannot be written does not need a test.

Exhaustiveness

A switch in Swift must handle every possible value. For an enum, that means every case, and the compiler checks:

enum Light {
    case red, yellow, green
}

func next(_ light: Light) -> Light {
    switch light {
    case .red: .green
    case .green: .yellow
    }
}

The error, “switch must be exhaustive”, is the compiler doing your bookkeeping. It pays off most when a type changes: add a case paused to DownloadState, and every switch that does not handle it stops compiling, each one pointing at code you need to update.

The pattern language

Each case in a switch is a pattern: a description of a shape that a value might have. Patterns can be combined and nested.

Tuples let one switch examine several values at once. The underscore _ matches anything:

for n in 1...15 {
    switch (n % 3, n % 5) {
    case (0, 0): print("FizzBuzz")
    case (0, _): print("Fizz")
    case (_, 0): print("Buzz")
    default: print(n)
    }
}

Value bindings with let name the parts they match, and a where clause adds any condition:

func describe(_ point: (Int, Int)) -> String {
    switch point {
    case (0, 0):
        "origin"
    case (let x, 0):
        "on the x-axis at \(x)"
    case (0, let y):
        "on the y-axis at \(y)"
    case let (x, y) where x == y:
        "on the diagonal"
    case let (x, y):
        "at (\(x), \(y))"
    }
}

print(describe((3, 0)))   // on the x-axis at 3
print(describe((2, 2)))   // on the diagonal

Cases are tried in order, and the first match wins, so (0, 0) is the origin even though it is also on the diagonal. case let (x, y) at the end matches everything, which is why this switch needs no default.

Ranges and expressions match by comparison:

func grade(_ score: Int) -> String {
    switch score {
    case 90...: "A"
    case 80..<90: "B"
    case 70..<80: "C"
    default: "try again"
    }
}

print(grade(95), grade(81), grade(12))   // A B try again

Nested enum patterns reach inside associated values, even several levels deep:

enum Payment {
    case cash
    case card(lastFour: Int)
    case transfer(from: String, reference: String)
}

func note(_ payment: Payment) -> String {
    switch payment {
    case .cash:
        "cash"
    case .card(lastFour: let digits) where digits < 1000:
        "card ending 0\(digits)"
    case .card(let digits):
        "card ending \(digits)"
    case .transfer(from: "Ada", _):
        "a transfer from Ada"
    case .transfer(let sender, _):
        "a transfer from someone else: \(sender)"
    }
}

print(note(.card(lastFour: 512)))              // card ending 0512
print(note(.transfer(from: "Ada", reference: "rent")))   // a transfer from Ada

"Ada" inside the pattern is an expression pattern: it matches only when the value equals it.

Matching outside switch

When you only care about one case, a whole switch is noise. if case tests a single pattern, guard case exits when it does not match, and for case loops over only the matching elements:

enum DownloadState {
    case notStarted
    case inProgress(fraction: Double)
    case finished(data: String)
    case failed(reason: String)
}

let states: [DownloadState] = [.finished(data: "abc"), .failed(reason: "offline"), .finished(data: "hello")]

if case .failed(let reason) = states[1] {
    print("error:", reason)                    // error: offline
}

var total = 0
for case .finished(let data) in states {
    total += data.count
}
print(total)                                   // 8

Optionals are enums (.none and .some), so there is a pattern for them too: x? matches a non-nil value and binds what is inside.

What would Swift print?

let readings: [Int?] = [3, nil, 4, nil, 5]
var sum = 0
for case let value? in readings {
    sum += value
}
print(sum)

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

Show answer and explanation

Answer12

case let value? matches only the non-nil elements and unwraps them, so the loop adds 3, 4, and 5. It is the pattern version of compactMap.

An expression tree

Algebraic data types are at their best for trees whose nodes are of different kinds. An arithmetic expression like (x + 1) × 3 is a tree: a multiplication whose left branch is an addition. Each kind of node is a case:

indirect enum Expr: Equatable {
    case number(Int)
    case variable
    case add(Expr, Expr)
    case multiply(Expr, Expr)
}

func evaluate(_ expr: Expr, x: Int) -> Int {
    switch expr {
    case .number(let n): n
    case .variable: x
    case .add(let left, let right): evaluate(left, x: x) + evaluate(right, x: x)
    case .multiply(let left, let right): evaluate(left, x: x) * evaluate(right, x: x)
    }
}

func show(_ expr: Expr) -> String {
    switch expr {
    case .number(let n): "\(n)"
    case .variable: "x"
    case .add(let left, let right): "(\(show(left)) + \(show(right)))"
    case .multiply(let left, let right): "\(show(left)) × \(show(right))"
    }
}

let e = Expr.multiply(.add(.variable, .number(1)), .number(3))
print(show(e), "=", evaluate(e, x: 4))   // (x + 1) × 3 = 15

indirect is needed because cases contain Exprs, as in Lesson 12. Declaring Equatable is enough for Swift to write == for the whole tree, comparing shapes and numbers recursively.

Every function over Expr has the same structure: one case per kind of node, recursion on the branches. That is Lesson 12’s “the function follows the data”, with the compiler now checking that no kind of node is forgotten.

Simplifying by shape

Pattern matching really shines when a function has to recognize combinations of nodes. Simplifying an expression means applying rules like “0 + e is e” and “2 + 3 is 5”. Each rule is a pattern:

indirect enum Expr: Equatable {
    case number(Int)
    case variable
    case add(Expr, Expr)
    case multiply(Expr, Expr)
}

func simplify(_ expr: Expr) -> Expr {
    switch expr {
    case .add(let left, let right):
        switch (simplify(left), simplify(right)) {
        case (.number(0), let other), (let other, .number(0)):
            return other
        case (.number(let a), .number(let b)):
            return .number(a + b)
        case let (a, b):
            return .add(a, b)
        }
    case .multiply(let left, let right):
        return .multiply(simplify(left), simplify(right))
    case .number, .variable:
        return expr
    }
}

let messy = Expr.add(.add(.number(2), .number(3)), .add(.number(0), .variable))
print(simplify(messy) == .add(.number(5), .variable))   // true

Three details make this work:

  • The branches are simplified first, then the results are matched. 0 + (2 + 3) becomes 0 + 5, which the first rule then turns into 5.
  • One case can list several patterns separated by commas, as long as each binds the same names with the same types. (.number(0), let other) and (let other, .number(0)) both bind other.
  • case .number, .variable: matches cases without binding their data.

The lab adds rules for multiplication.

What would Swift print?

indirect enum Expr {
    case number(Int)
    case add(Expr, Expr)
}
func count(_ e: Expr) -> Int {
    switch e {
    case .number: 1
    case .add(let a, let b): 1 + count(a) + count(b)
    }
}
print(count(.add(.add(.number(1), .number(2)), .number(3))))

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

Show answer and explanation

Answer5

Two add nodes and three number nodes. Every node is counted once, the same way Lesson 12 counted the nodes of a tree.

Immutable data

Functional programs rarely change a value in place. simplify does not modify its argument; it returns a new tree, and the old one is still there. Values that never change are easier to reason about: a function’s result depends only on its arguments, so you can test it by calling it, and share it freely without Lesson 13’s questions about who else can see a change.

Immutability is also cheaper than it sounds. A new tree can share the parts it did not change: the result of .add(.number(1), e) contains the same e, not a copy. Swift’s value types add copy-on-write on top, as Lesson 13 showed, so you can write functional code and let the language avoid the copying.

Generic algebraic types

Enums can be generic, like the structures in Lesson 16. Optional itself is defined in the standard library roughly like this:

enum Optional<Wrapped> {
    case none
    case some(Wrapped)
}

nil is .none, and if let is a convenient way of matching .some. You can write that match yourself:

let maybe: Int? = 42

switch maybe {
case .some(let value):
    print("got", value)   // got 42
case .none:
    print("nothing")
}

Another standard generic enum, Result<Success, Failure>, has the cases .success and .failure. It holds either an answer or an error, and it is one of the tools in Lesson 21.

Put the lines in order

Put the lines in order so the program prints 7.

  1. if case .node(let left, let value, let right) = tree {
  2. }
  3. indirect enum Tree { case leaf, node(Tree, Int, Tree) }
  4. print(sum(.node(.node(.leaf, 3, .leaf), 4, .leaf)))
  5. return sum(left) + value + sum(right)
  6. return 0
  7. func sum(_ tree: Tree) -> Int {
  8. }

Show the correct program
indirect enum Tree { case leaf, node(Tree, Int, Tree) }
func sum(_ tree: Tree) -> Int {
    if case .node(let left, let value, let right) = tree {
        return sum(left) + value + sum(right)
    }
    return 0
}
print(sum(.node(.node(.leaf, 3, .leaf), 4, .leaf)))

Lab 18: Algebraic data types

Q0: What would Swift print?

What would Swift print?

for n in [9, 10, 30, 7] {
    switch (n % 3, n % 5) {
    case (0, 0): print("FizzBuzz")
    case (0, _): print("Fizz")
    case (_, 0): print("Buzz")
    default: print(n)
    }
}

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

Show answer and explanation

AnswerFizz\nBuzz\nFizzBuzz\n7

30 matches (0, 0), the first case, before (0, _) gets a chance. Order matters: put the most specific patterns first.

What would Swift print?

let pair = (2, -2)
switch pair {
case let (a, b) where a + b == 0:
    print("opposites")
case let (a, b) where a == b:
    print("same")
case (_, let b) where b < 0:
    print("negative")
default:
    print("other")
}

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

Show answer and explanation

Answeropposites

The first case whose pattern and where clause both hold is chosen. The third case would also match, but it is never reached.

What would Swift print?

enum Command {
    case move(Int)
    case turn
}
let commands: [Command] = [.move(3), .turn, .move(4), .turn]
var steps = 0
for case .move(let n) in commands {
    steps += n
}
print(steps)

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

Show answer and explanation

Answer7

for case .move(let n) skips the turn commands entirely and binds n in the others.

Q1: Shapes

Write perimeter(_:) and area(_:) for this enum. A triangle is given by the lengths of its three sides, so its area needs Heron’s formula: with s = (a + b + c) / 2, the area is √(s(s − a)(s − b)(s − c)). The standard library’s squareRoot() method on Double does the square root.

enum Shape {
    case circle(radius: Double)
    case rectangle(width: Double, height: Double)
    case triangle(Double, Double, Double)
}
Show solution
enum Shape {
    case circle(radius: Double)
    case rectangle(width: Double, height: Double)
    case triangle(Double, Double, Double)
}

func perimeter(_ shape: Shape) -> Double {
    switch shape {
    case .circle(let r): 2 * Double.pi * r
    case .rectangle(let w, let h): 2 * (w + h)
    case .triangle(let a, let b, let c): a + b + c
    }
}

func area(_ shape: Shape) -> Double {
    switch shape {
    case .circle(let r):
        return Double.pi * r * r
    case .rectangle(let w, let h):
        return w * h
    case .triangle(let a, let b, let c):
        let s = (a + b + c) / 2
        return (s * (s - a) * (s - b) * (s - c)).squareRoot()
    }
}

assert(perimeter(.rectangle(width: 2, height: 3)) == 10)
assert(area(.triangle(3, 4, 5)) == 6)
assert(abs(area(.circle(radius: 1)) - 3.14159) < 0.0001)

The labels in the enum (radius:, width:) are optional in patterns; .rectangle(let w, let h) matches by position.

Q2: A vending machine

A vending machine sells snacks for 3 coins. It is either idle or has collected some coins. Write step(_:_:), which returns the machine’s next state and what it says, for these rules:

  • A coin adds to the coins collected. When the total reaches 3 or more, the machine says "snack" (plus " and change" if the total was over 3) and returns to idle; otherwise it says the new total.
  • A refund returns to idle, saying "refund 2" for 2 coins, or "nothing to refund" when idle.

Switch on the tuple (state, event).

enum Machine: Equatable {
    case idle
    case collected(Int)
}

enum Event {
    case coin
    case refund
}
Show solution
enum Machine: Equatable {
    case idle
    case collected(Int)
}

enum Event {
    case coin
    case refund
}

func step(_ state: Machine, _ event: Event) -> (Machine, String) {
    switch (state, event) {
    case (.idle, .coin):
        return step(.collected(0), .coin)
    case (.collected(let n), .coin) where n + 1 > 3:
        return (.idle, "snack and change")
    case (.collected(let n), .coin) where n + 1 == 3:
        return (.idle, "snack")
    case (.collected(let n), .coin):
        return (.collected(n + 1), "\(n + 1)")
    case (.idle, .refund):
        return (.idle, "nothing to refund")
    case (.collected(let n), .refund):
        return (.idle, "refund \(n)")
    }
}

var machine = Machine.idle
var said: [String] = []
for event: Event in [.coin, .coin, .refund, .refund, .coin, .coin, .coin] {
    let (next, message) = step(machine, event)
    machine = next
    said.append(message)
}
assert(said == ["1", "2", "refund 2", "nothing to refund", "1", "2", "snack"])
assert(machine == .idle)

With one coin at a time, the total can never pass 3, so "snack and change" cannot happen yet; the case is there because a rule someone adds later (a two-coin event, say) could reach it. Treating .idle as 0 coins collected keeps the coin rules in one place.

Q3: Simplifying products

Extend simplify with rules for multiplication: 0 × e and e × 0 are 0, 1 × e and e × 1 are e, and two numbers multiply out. Keep the addition rules.

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

func simplify(_ expr: Expr) -> Expr {
    switch expr {
    case .add(let left, let right):
        switch (simplify(left), simplify(right)) {
        case (.number(0), let other), (let other, .number(0)):
            return other
        case (.number(let a), .number(let b)):
            return .number(a + b)
        case let (a, b):
            return .add(a, b)
        }
    case .multiply(let left, let right):
        switch (simplify(left), simplify(right)) {
        case (.number(0), _), (_, .number(0)):
            return .number(0)
        case (.number(1), let other), (let other, .number(1)):
            return other
        case (.number(let a), .number(let b)):
            return .number(a * b)
        case let (a, b):
            return .multiply(a, b)
        }
    case .number, .variable:
        return expr
    }
}

let x = Expr.variable
assert(simplify(.multiply(.number(1), x)) == x)
assert(simplify(.multiply(x, .add(.number(0), .number(0)))) == .number(0))
assert(simplify(.multiply(.number(2), .add(.number(1), .number(3)))) == .number(8))
assert(simplify(.add(.multiply(.number(0), x), .multiply(x, .number(1)))) == x)

The zero rule comes before the one rule, so that 0 × 1 is 0 by the first rule; either order gives 0 here, but thinking about the order of rules is the habit that matters.

Q4: A binary search tree

Lesson 12 built a binary search tree from a structure. Build one from an enum instead, and write inserting(_:into:), contains(_:_:), and sorted(_:), which lists the values in order. inserting returns a new tree and leaves the old one unchanged.

indirect enum BST {
    case empty
    case node(BST, Int, BST)
}
Show solution
indirect enum BST {
    case empty
    case node(BST, Int, BST)
}

func inserting(_ value: Int, into tree: BST) -> BST {
    switch tree {
    case .empty:
        return .node(.empty, value, .empty)
    case .node(let left, let label, let right):
        if value < label {
            return .node(inserting(value, into: left), label, right)
        } else if value > label {
            return .node(left, label, inserting(value, into: right))
        }
        return tree
    }
}

func contains(_ tree: BST, _ value: Int) -> Bool {
    switch tree {
    case .empty:
        false
    case .node(let left, let label, let right):
        value == label || contains(value < label ? left : right, value)
    }
}

func sorted(_ tree: BST) -> [Int] {
    switch tree {
    case .empty: []
    case .node(let left, let label, let right): sorted(left) + [label] + sorted(right)
    }
}

let before = [5, 2, 8, 1, 9, 2].reduce(BST.empty) { inserting($1, into: $0) }
let after = inserting(7, into: before)
assert(sorted(before) == [1, 2, 5, 8, 9])
assert(sorted(after) == [1, 2, 5, 7, 8, 9])
assert(contains(after, 7) && !contains(before, 7))

inserting rebuilds only the nodes on the path to the new value; every other subtree is shared with the old tree. That is the sharing described under “Immutable data”, and why before still has no 7.

Q5: Rendering JSON

JSON is an algebraic data type. Write render(_:), which turns a value into JSON text with no spaces, listing an object’s keys in sorted order so the output is predictable. Strings are wrapped in double quotes; you do not need to escape anything inside them.

indirect enum JSON {
    case null
    case bool(Bool)
    case number(Int)
    case string(String)
    case array([JSON])
    case object([String: JSON])
}
Show solution
indirect enum JSON {
    case null
    case bool(Bool)
    case number(Int)
    case string(String)
    case array([JSON])
    case object([String: JSON])
}

func render(_ value: JSON) -> String {
    switch value {
    case .null:
        return "null"
    case .bool(let b):
        return b ? "true" : "false"
    case .number(let n):
        return "\(n)"
    case .string(let s):
        return "\"\(s)\""
    case .array(let items):
        return "[" + items.map(render).joined(separator: ",") + "]"
    case .object(let fields):
        let parts = fields.keys.sorted().map { key in "\"\(key)\":\(render(fields[key]!))" }
        return "{" + parts.joined(separator: ",") + "}"
    }
}

let lesson = JSON.object([
    "title": .string("ADTs"),
    "number": .number(19),
    "tags": .array([.string("enum"), .bool(true), .null]),
])
assert(render(lesson) == #"{"number":19,"tags":["enum",true,null],"title":"ADTs"}"#)

#"…"# is a raw string, in which quotation marks need no backslashes. The force unwrap in fields[key]! is safe because key came from the same dictionary’s keys.

Q6 (optional): Derivatives

Write derivative(_:), the derivative of an Expr with respect to x, then simplify the result. The rules: a number’s derivative is 0, x’s is 1, (f + g)′ = f′ + g′, and (f × g)′ = f × g′ + f′ × g.

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

func simplify(_ expr: Expr) -> Expr {
    switch expr {
    case .add(let left, let right):
        switch (simplify(left), simplify(right)) {
        case (.number(0), let other), (let other, .number(0)): return other
        case (.number(let a), .number(let b)): return .number(a + b)
        case let (a, b): return .add(a, b)
        }
    case .multiply(let left, let right):
        switch (simplify(left), simplify(right)) {
        case (.number(0), _), (_, .number(0)): return .number(0)
        case (.number(1), let other), (let other, .number(1)): return other
        case (.number(let a), .number(let b)): return .number(a * b)
        case let (a, b): return .multiply(a, b)
        }
    case .number, .variable:
        return expr
    }
}

func derivative(_ expr: Expr) -> Expr {
    switch expr {
    case .number:
        return .number(0)
    case .variable:
        return .number(1)
    case .add(let f, let g):
        return simplify(.add(derivative(f), derivative(g)))
    case .multiply(let f, let g):
        return simplify(.add(.multiply(f, derivative(g)), .multiply(derivative(f), g)))
    }
}

let x = Expr.variable
// (3x)′ = 3
assert(derivative(.multiply(.number(3), x)) == .number(3))
// (x × x)′ = x + x
assert(derivative(.multiply(x, x)) == .add(x, x))
// (x × x + 5x)′ = x + x + 5
assert(derivative(.add(.multiply(x, x), .multiply(.number(5), x))) == .add(.add(x, x), .number(5)))

This is one of the oldest programs in computer science textbooks: symbolic differentiation appears in Structure and Interpretation of Computer Programs, the book CS61A grew out of. Without simplify, the derivative of 3x would be 3 × 1 + 0 × x.

What’s next

An Expr tree plus a function that evaluates it is most of an interpreter. Next lesson adds the part that turns text into the tree, and builds a calculator for a small programming language.