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

Iterators and lazy sequences

How for-in really works, writing your own sequences and iterators, generator-style iterators from closures, and lazy sequences that compute only what you ask for, even forever.

CS61A
Lazy Evaluation · Generators · Composing Programs 4.2

Every sequence so far has been fully built before anyone used it: an array of all its elements, in memory. CS61A’s Lazy Evaluation and Generators lectures ask what happens if elements are only computed when someone asks for them. The answer includes sequences with no end.

Iterators

An iterator hands out the elements of a sequence one at a time. Its one method, next(), returns the next element, or nil when there are no more:

var iterator = [10, 20].makeIterator()
print(iterator.next()!)          // 10
print(iterator.next()!)          // 20
print(iterator.next() as Any)    // nil

An iterator remembers where it is, so each call changes it; that is why it is a var. A for-in loop is shorthand for exactly this: make an iterator, call next() until it returns nil.

Writing your own

A type becomes a sequence by conforming to the Sequence protocol, which the previous lesson introduced. The simplest way is to be your own iterator, conforming to IteratorProtocol as well:

struct Countdown: Sequence, IteratorProtocol {
    var current: Int

    mutating func next() -> Int? {
        guard current > 0 else {
            return nil
        }
        defer { current -= 1 }
        return current
    }
}

for n in Countdown(current: 3) {
    print(n)    // 3, 2, 1
}
print(Countdown(current: 5).map { $0 * 10 })   // [50, 40, 30, 20, 10]

defer runs its block just before the function returns, so next() returns the current value and then counts down. Once Countdown is a Sequence, it gets map, filter, contains, and everything else for free.

Generators from closures

Python’s generators are functions that yield values one at a time. Swift has no yield for this, but a closure that captures its state does the same job. AnyIterator wraps such a closure as an iterator:

func naturals() -> AnyIterator<Int> {
    var n = 0
    return AnyIterator {
        n += 1
        return n
    }
}

let numbers = naturals()
print(numbers.next()!, numbers.next()!, numbers.next()!)   // 1 2 3

This is Lesson 5’s counter, returning its values through the iterator protocol. The sequence never ends: next() never returns nil. That is fine, as long as nobody asks for all of it.

For the common case of “start here, compute the next from the previous”, the standard library has sequence(first:next:). It ends when the closure returns nil:

let powers = sequence(first: 1) { $0 * 2 }
print(Array(powers.prefix(5)))   // [1, 2, 4, 8, 16]

What would Swift print?

let hailstone = sequence(first: 6) { n in
    n == 1 ? nil : (n % 2 == 0 ? n / 2 : 3 * n + 1)
}
print(Array(hailstone))

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

Show answer and explanation

Answer[6, 3, 10, 5, 16, 8, 4, 2, 1]

Starting at 6: halve even numbers, triple-plus-one odd ones. When the value is 1, the closure returns nil, which ends the sequence, so Array can collect it all. This is Lesson 7’s hailstone sequence as data.

Lazy sequences

map and filter on an array are eager: they compute every element immediately and return a new array. Adding .lazy makes them compute each element only when it is needed:

What would Swift print?

let doubled = [1, 2, 3].lazy.map { x -> Int in
    print("map", x)
    return x * 2
}
print(doubled.first!)

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

Show answer and explanation

Answermap 1\n2

Creating doubled computes nothing. Asking for first runs the closure on the first element only, printing map 1, and the result is 2. Without .lazy, map 1, map 2, and map 3 would all print before the answer.

Laziness is what makes infinite sequences useful. 1... is the range of all integers from 1 upward; filtering it eagerly would never finish, but a lazy filter can be asked for just the first few matches:

func isPrime(_ n: Int) -> Bool {
    n > 1 && !(2..<n).contains { $0 * $0 <= n && n % $0 == 0 }
}

let primes = (1...).lazy.filter(isPrime)
print(Array(primes.prefix(6)))   // [2, 3, 5, 7, 11, 13]

prefix(6) is lazy too; only Array(...) finally asks for elements, and it stops after six.

What would Swift print?

let evens = (0...).lazy.map { $0 * 2 }.filter { $0 % 3 != 0 }
print(Array(evens.prefix(4)))

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

Show answer and explanation

Answer[2, 4, 8, 10]

The even numbers are 0, 2, 4, 6, 8, 10, …; the filter drops multiples of 3, which removes 0 and 6. The first four that remain are 2, 4, 8, and 10.

More tools for endless sequences

A few more building blocks work naturally with infinite sequences:

// zip stops at the shorter sequence, so an endless range can number anything.
print(Array(zip(1..., ["a", "b", "c"])))              // [(1, "a"), (2, "b"), (3, "c")]

// prefix(while:) takes elements until the condition first fails.
print(Array((1...).lazy.map { $0 * $0 }.prefix(while: { $0 < 50 })))   // [1, 4, 9, 16, 25, 36, 49]

// stride counts by any step, in either direction.
print(Array(stride(from: 10, through: 0, by: -5)))    // [10, 5, 0]

sequence(state:next:) generalizes sequence(first:next:): it carries any state you like between elements, which is how a generator with more than one variable is written. Here, the Fibonacci numbers:

let fibonacci = sequence(state: (0, 1)) { (state: inout (Int, Int)) -> Int? in
    let current = state.0
    state = (state.1, state.0 + state.1)
    return current
}
print(Array(fibonacci.prefix(10)))   // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

What would Swift print?

var checked: [Int] = []
let multiplesOfThree = (1...10).lazy.filter { n -> Bool in
    checked.append(n)
    return n % 3 == 0
}
print(multiplesOfThree.first!, checked)

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

Show answer and explanation

Answer3 [1, 2, 3]

The lazy filter tests elements only until first has its answer: 1 and 2 fail, 3 passes, and the numbers from 4 onward are never checked.

Put the lines in order

Put the lines in order so the program prints [3, 2, 1].

  1. var current: Int
  2. return nil
  3. mutating func next() -> Int? {
  4. }
  5. if current == 0 {
  6. struct Countdown: Sequence, IteratorProtocol {
  7. current -= 1
  8. }
  9. return current + 1
  10. }
  11. print(Array(Countdown(current: 3)))

Show the correct program
struct Countdown: Sequence, IteratorProtocol {
    var current: Int
    mutating func next() -> Int? {
        if current == 0 {
            return nil
        }
        current -= 1
        return current + 1
    }
}
print(Array(Countdown(current: 3)))

Lab 16: Sequences on demand

Q0: What would Swift print?

What would Swift print?

var iterator = [1, 2, 3].makeIterator()
_ = iterator.next()
for n in IteratorSequence(iterator) {
    print(n, terminator: " ")
}
print()

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

Show answer and explanation

Answer2 3

The first next() used up the 1. Wrapping the iterator in a sequence and looping continues from where it left off.

What would Swift print?

let evens = sequence(first: 0) { $0 + 2 }
print(Array(evens.prefix(3)), evens.first(where: { $0 > 9 })!)

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

Show answer and explanation

Answer[0, 2, 4] 10

The sequence never ends, but prefix(3) and first(where:) each stop as soon as they have what they need.

What would Swift print?

let squares = [1, 2, 3].lazy.map { n -> Int in
    print("computing", n)
    return n * n
}
print(squares[1])

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

Show answer and explanation

Answercomputing 2\n4

A lazy map over an array can jump straight to a position. Reading element 1 computes only that element, the square of 2.

Q1: A range with a step

Write a sequence Steps that yields start, start + step, … up to but not including end. Assume step is positive.

Show solution
struct Steps: Sequence, IteratorProtocol {
    var current: Int
    let end: Int
    let step: Int

    init(from start: Int, to end: Int, by step: Int) {
        precondition(step > 0, "step must be positive")
        current = start
        self.end = end
        self.step = step
    }

    mutating func next() -> Int? {
        guard current < end else {
            return nil
        }
        defer { current += step }
        return current
    }
}

assert(Array(Steps(from: 0, to: 10, by: 3)) == [0, 3, 6, 9])
assert(Array(Steps(from: 5, to: 5, by: 1)) == [])
assert(Steps(from: 1, to: 100, by: 2).reduce(0, +) == 2500)

The standard library’s stride(from:to:by:) does the same, and handles negative steps too.

Q2: Fibonacci forever

Write fibonacci(), returning an AnyIterator<Int> that produces 0, 1, 1, 2, 3, 5, … without end.

func fibonacci() -> AnyIterator<Int> {
    // your code here
}
Show solution
func fibonacci() -> AnyIterator<Int> {
    var current = 0
    var next = 1
    return AnyIterator {
        defer { (current, next) = (next, current + next) }
        return current
    }
}

let fibs = fibonacci()
assert((1...8).map { _ in fibs.next()! } == [0, 1, 1, 2, 3, 5, 8, 13])

This is Lesson 5’s makeFibber, wrapped as an iterator so it works with everything that accepts one.

Q3: The first perfect squares that are even

Using a lazy sequence of all positive integers, return the first n perfect squares that are even.

func evenSquares(_ n: Int) -> [Int] {
    // your code here
}
Show solution
func evenSquares(_ n: Int) -> [Int] {
    Array((1...).lazy.map { $0 * $0 }.filter { $0 % 2 == 0 }.prefix(n))
}

assert(evenSquares(4) == [4, 16, 36, 64])
assert(evenSquares(0) == [])

Without .lazy, (1...).map would try to square every positive integer and never finish.

Q4: Interleave

Write interleave(_:_:), which returns an iterator that alternates between two arrays, starting with the first. When one runs out, it continues with the rest of the other.

func interleave(_ a: [Int], _ b: [Int]) -> AnyIterator<Int> {
    // your code here
}
Show solution
func interleave(_ a: [Int], _ b: [Int]) -> AnyIterator<Int> {
    var first = a.makeIterator()
    var second = b.makeIterator()
    var takeFirst = true
    return AnyIterator {
        defer { takeFirst.toggle() }
        if takeFirst {
            return first.next() ?? second.next()
        }
        return second.next() ?? first.next()
    }
}

assert(Array(IteratorSequence(interleave([1, 3, 5], [2, 4]))) == [1, 2, 3, 4, 5])
assert(Array(IteratorSequence(interleave([], [7, 8]))) == [7, 8])
assert(Array(IteratorSequence(interleave([1], []))) == [1])

?? falls back to the other iterator when the preferred one is empty, and the result is nil only when both are. toggle() flips a Bool in place.

Q5: Running sums, lazily

Using sequence(state:next:), write runningSums(_:), which returns the running sums of an array without building them with a loop: runningSums([1, 2, 3, 4]) is [1, 3, 6, 10].

Show solution
func runningSums(_ values: [Int]) -> [Int] {
    let sums = sequence(state: (values.makeIterator(), 0)) { state -> Int? in
        guard let next = state.0.next() else {
            return nil
        }
        state.1 += next
        return state.1
    }
    return Array(sums)
}

assert(runningSums([1, 2, 3, 4]) == [1, 3, 6, 10])
assert(runningSums([]) == [])

The state is a pair: an iterator over the input and the sum so far. Each step reads one input, updates the sum, and returns it.

Q6 (optional): Hamming numbers

The Hamming numbers are the positive integers with no prime factors other than 2, 3, and 5: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, … Write hamming(_:), returning the first n in increasing order, without testing every integer.

Show solution
func hamming(_ n: Int) -> [Int] {
    var numbers = [1]
    var i2 = 0
    var i3 = 0
    var i5 = 0
    while numbers.count < n {
        let next = min(numbers[i2] * 2, numbers[i3] * 3, numbers[i5] * 5)
        numbers.append(next)
        if next == numbers[i2] * 2 { i2 += 1 }
        if next == numbers[i3] * 3 { i3 += 1 }
        if next == numbers[i5] * 5 { i5 += 1 }
    }
    return Array(numbers.prefix(n))
}

assert(hamming(10) == [1, 2, 3, 4, 5, 6, 8, 9, 10, 12])
assert(hamming(15).last == 24)
assert(hamming(1) == [1])

Every Hamming number after 1 is 2, 3, or 5 times a smaller one. Three positions track the next candidate from each multiplier, and the smallest candidate comes next. All three positions advance on a tie, such as 6 = 2 × 3 = 3 × 2, which keeps duplicates out. This is three lazy sequences merged in order.

What’s next

Next lesson: efficiency. How to count the work a program does, and how memoization turns Lesson 8’s exponential fib into a fast one.