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

IntLists

Practice with naked linked lists: printing, structural equality, catenating with and without destroying the originals, squaring primes in place, reversing, and detecting a cycle.

This homework goes with Lessons 27 and 28, like CS61B’s IntList homework. Start hw12.swift with this class, and add each answer to it or after it. Write loops, not recursion, for anything that walks a whole list, unless the problem says otherwise.

final class IntList {
    var first: Int
    var rest: IntList?

    init(_ first: Int, _ rest: IntList?) {
        self.first = first
        self.rest = rest
    }

    static func of(_ values: Int...) -> IntList? {
        values.reversed().reduce(nil) { IntList($1, $0) }
    }
}

Q1: Printing

Make IntList conform to CustomStringConvertible, printing 1 -> 2 -> 3.

Show solution
final class IntList {
    var first: Int
    var rest: IntList?
    init(_ first: Int, _ rest: IntList?) {
        self.first = first
        self.rest = rest
    }
    static func of(_ values: Int...) -> IntList? {
        values.reversed().reduce(nil) { IntList($1, $0) }
    }
}

extension IntList: CustomStringConvertible {
    var description: String {
        var parts: [String] = []
        var node: IntList? = self
        while let current = node {
            parts.append(String(current.first))
            node = current.rest
        }
        return parts.joined(separator: " -> ")
    }
}

assert(IntList.of(1, 2, 3)!.description == "1 -> 2 -> 3")
assert("\(IntList(7, nil))" == "7")

Q2: Structural equality

Make IntList Equatable: two lists are equal if they have the same items in the same order. Then explain why == and === now give different answers for two separately built lists.

Show solution
final class IntList {
    var first: Int
    var rest: IntList?
    init(_ first: Int, _ rest: IntList?) {
        self.first = first
        self.rest = rest
    }
    static func of(_ values: Int...) -> IntList? {
        values.reversed().reduce(nil) { IntList($1, $0) }
    }
}

extension IntList: Equatable {
    static func == (lhs: IntList, rhs: IntList) -> Bool {
        var a: IntList? = lhs
        var b: IntList? = rhs
        while let x = a, let y = b {
            if x.first != y.first {
                return false
            }
            a = x.rest
            b = y.rest
        }
        return a == nil && b == nil
    }
}

let one = IntList.of(1, 2, 3)!
let two = IntList.of(1, 2, 3)!
assert(one == two && !(one === two))
assert(one != IntList.of(1, 2)! && IntList.of(1, 2)! != one)

== compares items and === compares identity: two lists built separately contain the same values in different objects. The last check after the loop catches lists of different lengths, in either order.

Q3: Catenating, two ways

Write catenate(_:_:), which returns a new list containing the items of a followed by those of b and changes neither, and dcatenate(_:_:), which destructively links the end of a to b and returns the result.

Show solution
final class IntList {
    var first: Int
    var rest: IntList?
    init(_ first: Int, _ rest: IntList?) {
        self.first = first
        self.rest = rest
    }
    static func of(_ values: Int...) -> IntList? {
        values.reversed().reduce(nil) { IntList($1, $0) }
    }
    var items: [Int] {
        var result: [Int] = []
        var node: IntList? = self
        while let current = node {
            result.append(current.first)
            node = current.rest
        }
        return result
    }
}

func catenate(_ a: IntList?, _ b: IntList?) -> IntList? {
    guard let a else { return b }
    let head = IntList(a.first, nil)
    var tail = head
    var node = a.rest
    while let current = node {
        tail.rest = IntList(current.first, nil)
        tail = tail.rest!
        node = current.rest
    }
    tail.rest = b
    return head
}

func dcatenate(_ a: IntList?, _ b: IntList?) -> IntList? {
    guard let a else { return b }
    var tail = a
    while let next = tail.rest {
        tail = next
    }
    tail.rest = b
    return a
}

let a = IntList.of(1, 2)
let b = IntList.of(3, 4)
let joined = catenate(a, b)!
assert(joined.items == [1, 2, 3, 4] && a!.items == [1, 2])
let destroyed = dcatenate(a, b)!
assert(destroyed === a && a!.items == [1, 2, 3, 4])
assert(catenate(nil, b)!.items == [3, 4] && dcatenate(a, nil)!.items == [1, 2, 3, 4])

catenate copies a’s nodes but shares b’s: nothing changes b, so sharing is safe as long as nobody later changes b destructively. Whether that is acceptable is exactly the kind of decision a data structure’s documentation must state.

Q4: Squaring the primes

Write squarePrimes(_:), which destructively squares every prime number in the list and returns whether any item changed.

Show solution
final class IntList {
    var first: Int
    var rest: IntList?
    init(_ first: Int, _ rest: IntList?) {
        self.first = first
        self.rest = rest
    }
    static func of(_ values: Int...) -> IntList? {
        values.reversed().reduce(nil) { IntList($1, $0) }
    }
    var items: [Int] {
        var result: [Int] = []
        var node: IntList? = self
        while let current = node {
            result.append(current.first)
            node = current.rest
        }
        return result
    }
}

func isPrime(_ n: Int) -> Bool {
    guard n >= 2 else { return false }
    var d = 2
    while d * d <= n {
        if n % d == 0 { return false }
        d += 1
    }
    return true
}

func squarePrimes(_ list: IntList?) -> Bool {
    var changed = false
    var node = list
    while let current = node {
        if isPrime(current.first) {
            current.first *= current.first
            changed = true
        }
        node = current.rest
    }
    return changed
}

let list = IntList.of(14, 15, 16, 17, 18)!
assert(squarePrimes(list) && list.items == [14, 15, 16, 289, 18])
assert(!squarePrimes(IntList.of(1, 4, 9)))
assert(!squarePrimes(nil))

Q5: Reverse

Write reversed(_:), which destructively reverses a list and returns its new first node, creating no nodes. Then write a recursive version.

Show solution
final class IntList {
    var first: Int
    var rest: IntList?
    init(_ first: Int, _ rest: IntList?) {
        self.first = first
        self.rest = rest
    }
    static func of(_ values: Int...) -> IntList? {
        values.reversed().reduce(nil) { IntList($1, $0) }
    }
    var items: [Int] {
        var result: [Int] = []
        var node: IntList? = self
        while let current = node {
            result.append(current.first)
            node = current.rest
        }
        return result
    }
}

func reversed(_ list: IntList?) -> IntList? {
    var done: IntList? = nil
    var remaining = list
    while let node = remaining {
        remaining = node.rest
        node.rest = done
        done = node
    }
    return done
}

func reversedRecursive(_ list: IntList?) -> IntList? {
    guard let list, let rest = list.rest else { return list }
    let head = reversedRecursive(rest)
    rest.rest = list       // the old second node now points back at the first
    list.rest = nil
    return head
}

let a = IntList.of(1, 2, 3, 4)!
let r = reversed(a)!
assert(r.items == [4, 3, 2, 1] && a.items == [1])   // a is now the last node
let back = reversedRecursive(r)!
assert(back === a && back.items == [1, 2, 3, 4])
assert(reversed(nil) == nil)

The recursive version reverses the rest first; afterwards, the old second node is the last node of the reversed rest, so pointing it back at the old first node finishes the job. The test a.items == [1] shows what “destructive” means: the variable a still points at the same node, which is now at the end.

Q6 (optional): Detecting a cycle

A buggy destructive function might make a list point back into itself, so that walking it never ends. Write hasCycle(_:), which detects this using only a constant amount of extra memory: move one reference one step at a time and another two steps at a time. If there is a cycle, the fast one eventually lands on the slow one.

Show solution
final class IntList {
    var first: Int
    var rest: IntList?
    init(_ first: Int, _ rest: IntList?) {
        self.first = first
        self.rest = rest
    }
    static func of(_ values: Int...) -> IntList? {
        values.reversed().reduce(nil) { IntList($1, $0) }
    }
}

func hasCycle(_ list: IntList?) -> Bool {
    var slow = list
    var fast = list
    while let next = fast?.rest, let nextNext = next.rest {
        slow = slow?.rest
        fast = nextNext
        if slow === fast {
            return true
        }
    }
    return false
}

let straight = IntList.of(1, 2, 3, 4, 5)!
assert(!hasCycle(straight) && !hasCycle(nil))

let looped = IntList.of(1, 2, 3, 4, 5)!
var last = looped
while let next = last.rest {
    last = next
}
last.rest = looped.rest!.rest      // 5 points back to 3
assert(hasCycle(looped))
last.rest = nil                    // break the cycle, so ARC can free the nodes

This is Floyd’s “tortoise and hare” algorithm. Once both are inside the cycle, the hare gains one step on the tortoise per move, so it cannot jump over it and must land on it within one trip around. Comparing with === asks about identity, not value, which is the question here: two different nodes could hold the same number. The last line breaks the cycle, because a cycle of strong references would otherwise never be freed.