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

Functional abstraction

Generalizing with functions, iterative improvement and Newton’s method, contracts written as documentation and preconditions, and functions that wrap other functions.

CS61A
Abstraction · Function Examples · Composing Programs 1.6
Swift book
Functions · Closures

A function is an abstraction when you can use it without knowing how it works. max(3, 9) is 9; you have never needed to see its body. This lesson is about writing functions that others can use the same way: general enough to reuse, with a clear promise about what they do.

Generalizing

Lesson 4 turned three sums into one summation by making the varying part a parameter. The same function handles much less obvious terms. This sum converges, very slowly, to π:

8/(1·3) + 8/(5·7) + 8/(9·11) + ⋯
func summation(_ n: Int, _ term: (Int) -> Double) -> Double {
    var total = 0.0
    for k in 1...n {
        total += term(k)
    }
    return total
}

func piSum(_ n: Int) -> Double {
    summation(n) { k in 8.0 / Double((4 * k - 3) * (4 * k - 1)) }
}

print(piSum(1000))   // 3.141092653621038

summation now adds Doubles, and piSum only has to say what the kth term is.

Iterative improvement

Many numerical methods follow one pattern: start with a guess, and keep improving it until it is close enough. The pattern itself can be a function that takes the two varying parts, how to improve and how to judge, as arguments:

func improve(_ update: (Double) -> Double, _ close: (Double) -> Bool, _ guess: Double = 1) -> Double {
    var guess = guess
    while !close(guess) {
        guess = update(guess)
    }
    return guess
}

// The golden ratio is the positive number x with x * x == x + 1.
let golden = improve({ x in 1 / x + 1 }, { x in abs(x * x - (x + 1)) < 1e-10 })
print(golden)   // 1.6180339887802426

guess: Double = 1 gives the parameter a default value, so callers can leave it out.

Newton’s method is an improvement rule for square roots: a better guess for √a is the average of x and a / x.

func improve(_ update: (Double) -> Double, _ close: (Double) -> Bool, _ guess: Double = 1) -> Double {
    var guess = guess
    while !close(guess) { guess = update(guess) }
    return guess
}

func squareRoot(_ a: Double) -> Double {
    improve({ x in (x + a / x) / 2 }, { x in abs(x * x - a) < 1e-10 })
}

print(squareRoot(2))     // 1.4142135623746899
print(squareRoot(256))   // 16.00000000000039

The second result is not exactly 16: close accepts any guess whose square is within 10⁻¹⁰ of 256. Floating-point answers are compared with a tolerance, never with ==.

Put the lines in order

Put the lines in order. improve should keep updating the guess until close accepts it; the program prints true.

  1. }
  2. var guess = 1.0
  3. func improve(_ update: (Double) -> Double, _ close: (Double) -> Bool) -> Double {
  4. while !close(guess) {
  5. return guess
  6. guess = update(guess)
  7. let golden = improve({ 1 / $0 + 1 }, { abs($0 * $0 - ($0 + 1)) < 1e-10 })
  8. print(golden > 1.618 && golden < 1.619)
  9. }

Show the correct program
func improve(_ update: (Double) -> Double, _ close: (Double) -> Bool) -> Double {
    var guess = 1.0
    while !close(guess) {
        guess = update(guess)
    }
    return guess
}
let golden = improve({ 1 / $0 + 1 }, { abs($0 * $0 - ($0 + 1)) < 1e-10 })
print(golden > 1.618 && golden < 1.619)

Newton’s method in general

The square-root update is one case of a general method. To find a zero of any differentiable function f, a better guess than x is x − f(x) / f′(x): follow the tangent line down to where it crosses zero. The derivative can be approximated numerically, so one higher-order function solves every such equation:

func findZero(_ f: @escaping (Double) -> Double, _ guess: Double = 1) -> Double {
    let dx = 1e-6
    var x = guess
    while abs(f(x)) > 1e-10 {
        let slope = (f(x + dx) - f(x)) / dx
        x = x - f(x) / slope
    }
    return x
}

print(findZero({ $0 * $0 - 2 }))              // about 1.4142135623754
print(findZero({ $0 * $0 * $0 - 27 }, 5))     // about 3.0

findZero knows nothing about square or cube roots. The caller describes the problem as “where is this function zero?” and the method does the rest. That separation is the reason to write it as a higher-order function.

A function’s contract

To use a function without reading its body, you need to know three things: what it takes, what it returns, and anything it assumes. Swift writes the first two in the signature. The rest belongs in a documentation comment, written with /// directly above the function:

/// Returns the number of ways to choose `k` items from `n`.
///
/// - Precondition: `0 <= k` and `k <= n`.
func choose(_ n: Int, _ k: Int) -> Int {
    precondition(0 <= k && k <= n, "k must be between 0 and n")
    var result = 1
    for i in 0..<k {
        result = result * (n - i) / (i + 1)
    }
    return result
}

print(choose(5, 2))   // 10

Xcode and other editors show these comments when you use the function. The precondition line turns the assumption into a check: if a caller breaks the contract, the program stops right there, instead of returning a meaningless number.

What would Swift print?

func half(_ n: Int) -> Int {
    precondition(n % 2 == 0, "n must be even")
    return n / 2
}
print(half(half(10)))

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

Show answer and explanation

AnswerError

The inner call half(10) returns 5. The outer call receives 5, which is odd, so the precondition fails and the program stops with a runtime error. Nothing is printed: print never receives a value.

Tests as examples

CS61A writes examples as doctests. In Swift, assert lines play the same role in a lab file: assert(choose(5, 2) == 10) does nothing when the answer is right and stops the program when it is wrong. In Unit 3 we will move to Swift’s testing library.

Debugging

CS61A gives debugging its own lecture; here are the habits worth starting now.

  • Read the first error. A compile error names a file, line, and column. Later errors are often consequences of the first, so fix it and compile again.
  • Print what you assume. A print that shows the arguments and the result of a function is the quickest way to find where reality and your expectations part. Remove it once you know.
  • Assert what must be true. An assert placed where a condition must hold turns a wrong result far away into a stop right where things went wrong.
  • Shrink the input. If f(1000) is wrong, try f(0), f(1), f(2). The smallest failing case is usually the base case or the boundary.

The trace function below automates the second habit for any function.

Functions that wrap functions

A higher-order function can add behavior to any function without changing it. trace prints each argument before calling the function it wraps, which is handy when debugging:

func trace(_ f: @escaping (Int) -> Int) -> (Int) -> Int {
    return { x in
        print("->", x)
        return f(x)
    }
}

let tracedSquare = trace { $0 * $0 }
print(tracedSquare(3))

What would Swift print?

func trace(_ f: @escaping (Int) -> Int) -> (Int) -> Int {
    return { x in
        print("->", x)
        return f(x)
    }
}
let t = trace { $0 + 1 }
print(t(t(1)))

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

Show answer and explanation

Answer-> 1\n-> 2\n3

The inner call t(1) runs first: it prints -> 1 and returns 2. Then t(2) prints -> 2 and returns 3, which the outer print writes.

Searching

search finds the smallest non-negative integer for which a condition holds:

func search(_ condition: (Int) -> Bool) -> Int {
    var x = 0
    while !condition(x) {
        x += 1
    }
    return x
}

print(search { $0 * $0 > 30 })   // 6

What would Swift print?

func search(_ condition: (Int) -> Bool) -> Int {
    var x = 0
    while !condition(x) {
        x += 1
    }
    return x
}
print(search { $0 % 7 == 3 && $0 > 10 })

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

Show answer and explanation

Answer17

The condition asks for a number above 10 that leaves remainder 3 when divided by 7. The candidates with remainder 3 are 3, 10, 17, …; the first one above 10 is 17.

Lab 5: Abstraction

Q0: What would Swift print?

What would Swift print?

func improve(_ update: (Int) -> Int, _ done: (Int) -> Bool, _ start: Int) -> Int {
    var x = start
    while !done(x) {
        x = update(x)
    }
    return x
}
print(improve({ $0 * 2 }, { $0 > 100 }, 3))

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

Show answer and explanation

Answer192

Starting from 3 and doubling: 6, 12, 24, 48, 96, 192. The first value above 100 is 192.

What would Swift print?

func search(_ condition: (Int) -> Bool) -> Int {
    var x = 0
    while !condition(x) {
        x += 1
    }
    return x
}
print(search { $0 * $0 >= 50 }, search { _ in true })

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

Show answer and explanation

Answer8 0

7 × 7 is 49, too small, so the first square at least 50 is 8 × 8. A condition that is always true is satisfied immediately, at 0.

What would Swift print?

func check(_ n: Int) -> Int {
    assert(n > 0, "n must be positive")
    return n * 2
}
print(check(3))
print(check(0))

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

Show answer and explanation

AnswerError

check(3) prints 6, but then check(0) fails its assertion and stops the program. A crash anywhere makes the whole answer Error.

Q1: Inverse

Using search, write inverse(f): given a function f that is increasing on the non-negative integers, return a function g such that g(f(x)) == x.

func inverse(_ f: @escaping (Int) -> Int) -> (Int) -> Int {
    // your code here
}
Show solution
func search(_ condition: (Int) -> Bool) -> Int {
    var x = 0
    while !condition(x) { x += 1 }
    return x
}

func inverse(_ f: @escaping (Int) -> Int) -> (Int) -> Int {
    return { y in search { x in f(x) == y } }
}

let squareRoot = inverse { $0 * $0 }
assert(squareRoot(16) == 4)
assert(squareRoot(144) == 12)
let halve = inverse { $0 * 2 }
assert(halve(10) == 5)

The inverse of f at y is “the x whose f(x) is y”, which is exactly a search. If y is not a value f ever takes, the search never stops, which is why the problem promises y is in range.

Q2: Count the calls

Write countCalls(f), which returns two functions in a tuple: call, which behaves exactly like f, and count, which returns how many times call has been called.

func countCalls(_ f: @escaping (Int) -> Int) -> (call: (Int) -> Int, count: () -> Int) {
    // your code here
}
Show solution
func countCalls(_ f: @escaping (Int) -> Int) -> (call: (Int) -> Int, count: () -> Int) {
    var calls = 0
    let call = { (x: Int) -> Int in
        calls += 1
        return f(x)
    }
    return (call, { calls })
}

let counted = countCalls { $0 * 10 }
assert(counted.count() == 0)
assert(counted.call(2) == 20)
assert(counted.call(3) == 30)
assert(counted.count() == 2)

Both closures capture the same calls variable from the frame of this call to countCalls, so count sees the updates that call makes.

Q3: Cube roots

Using improve from this lesson, write cubeRoot(_:) with Newton’s update for cube roots: a better guess for ∛a is (2x + a / x²) / 3. Stop when |x³ − a| < 10⁻¹⁰.

Show solution
func improve(_ update: (Double) -> Double, _ close: (Double) -> Bool, _ guess: Double = 1) -> Double {
    var guess = guess
    while !close(guess) { guess = update(guess) }
    return guess
}

func cubeRoot(_ a: Double) -> Double {
    improve({ x in (2 * x + a / (x * x)) / 3 }, { x in abs(x * x * x - a) < 1e-10 })
}

assert(abs(cubeRoot(27) - 3) < 1e-9)
assert(abs(cubeRoot(2) * cubeRoot(2) * cubeRoot(2) - 2) < 1e-9)

Only the two small closures change; the loop, the stopping logic, and the default starting guess all come from improve.

Q4: Any root

Using improve, write nthRoot(_:_:), the nth root of a positive number. Newton’s update for the nth root of a is ((n − 1)·x + a / xⁿ⁻¹) / n. Stop when |xⁿ − a| < 10⁻⁹.

Show solution
func improve(_ update: (Double) -> Double, _ close: (Double) -> Bool, _ guess: Double = 1) -> Double {
    var guess = guess
    while !close(guess) { guess = update(guess) }
    return guess
}

func power(_ x: Double, _ k: Int) -> Double {
    var result = 1.0
    for _ in 0..<k {
        result *= x
    }
    return result
}

func nthRoot(_ a: Double, _ n: Int) -> Double {
    let degree = Double(n)
    return improve(
        { x in ((degree - 1) * x + a / power(x, n - 1)) / degree },
        { x in abs(power(x, n) - a) < 1e-9 }
    )
}

assert(abs(nthRoot(32, 5) - 2) < 1e-9)
assert(abs(nthRoot(81, 4) - 3) < 1e-9)
assert(abs(nthRoot(2, 2) * nthRoot(2, 2) - 2) < 1e-9)

With n of 2 this is the square-root update from the lesson, and with n of 3 the cube-root update from Q3. One general function replaces both.

Q5: Smoothing

Smoothing a function f means replacing each value f(x) with the average of f(x − dx), f(x), and f(x + dx). Write smooth(_:dx:), which returns the smoothed function, with dx defaulting to 0.001.

func smooth(_ f: @escaping (Double) -> Double, dx: Double = 0.001) -> (Double) -> Double {
    // your code here
}
Show solution
func smooth(_ f: @escaping (Double) -> Double, dx: Double = 0.001) -> (Double) -> Double {
    return { x in (f(x - dx) + f(x) + f(x + dx)) / 3 }
}

let smoothSquare = smooth { $0 * $0 }
assert(abs(smoothSquare(2) - 4.000000666666667) < 1e-12)
assert(smooth({ _ in 7 })(100) == 7)   // a constant stays constant

For x², smoothing adds 2·dx²/3 to every value, which is the tiny difference from 4 in the first check.

Q6 (optional): Smooth it again

Write nFoldSmooth(_:_:), which smooths a function n times. Use smooth and no loops over values, only a loop or reduce over the number of times.

Show solution
func smooth(_ f: @escaping (Double) -> Double, dx: Double = 0.001) -> (Double) -> Double {
    return { x in (f(x - dx) + f(x) + f(x + dx)) / 3 }
}

func nFoldSmooth(_ f: @escaping (Double) -> Double, _ n: Int) -> (Double) -> Double {
    (0..<n).reduce(f) { smoothed, _ in smooth(smoothed) }
}

assert(abs(nFoldSmooth({ $0 * $0 }, 2)(2) - 4.0000013333333335) < 1e-12)
assert(nFoldSmooth({ $0 * 3 }, 0)(5) == 15)   // zero times: unchanged

Each step wraps the previous function in another smooth. Nothing is computed until the final function is called, at which point every layer calls the one inside it three times.

What’s next

Next lesson: recursion, where a function’s body calls the function itself.