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

Interpreters and errors

A tokenizer that reports where it failed, a stack calculator with typed errors, a parser for boolean formulas, a configuration reader that collects every problem, and a tiny Forth.

This homework uses Lessons 20 and 21. Put everything in hw09.swift with the assert lines, and run it. Every function that can fail here throws a specific error type; the tests check the error as well as the value, since a wrong error message is a bug too.

Q1: Where did it go wrong?

Write tokenize(_:) for arithmetic like 12 + (3*4). Tokens are whole numbers, the operators + - * /, and parentheses; spaces separate tokens but are not tokens. Any other character throws .unexpected(character, at: index), where index counts characters from 0.

enum Token: Equatable {
    case number(Int)
    case op(Character)
    case open, close
}

enum LexError: Error, Equatable {
    case unexpected(Character, at: Int)
}
Show solution
enum Token: Equatable {
    case number(Int)
    case op(Character)
    case open, close
}

enum LexError: Error, Equatable {
    case unexpected(Character, at: Int)
}

func tokenize(_ text: String) throws(LexError) -> [Token] {
    var tokens: [Token] = []
    var digits = ""
    for (index, character) in text.enumerated() {
        if character.isNumber {
            digits.append(character)
            continue
        }
        if let n = Int(digits) {
            tokens.append(.number(n))
            digits = ""
        }
        switch character {
        case "+", "-", "*", "/": tokens.append(.op(character))
        case "(": tokens.append(.open)
        case ")": tokens.append(.close)
        case " ": break
        default: throw .unexpected(character, at: index)
        }
    }
    if let n = Int(digits) {
        tokens.append(.number(n))
    }
    return tokens
}

assert(try! tokenize("12 + (3*4)") == [.number(12), .op("+"), .open, .number(3), .op("*"), .number(4), .close])
assert(try! tokenize("") == [])
do {
    _ = try tokenize("2 + x")
    assert(false, "should have thrown")
} catch {
    assert(error == .unexpected("x", at: 4))
}

enumerated() pairs each character with its position, so the error can say exactly where the problem is. A message like “unexpected x at 4” is the difference between a user fixing their input in seconds and guessing.

Q2: A stack calculator

In reverse Polish notation, operators come after their operands: 3 4 + 2 * means (3 + 4) × 2. It needs no parentheses, and it is evaluated with a stack: push each number; for an operator, pop two numbers, apply it, and push the result. At the end exactly one number must remain.

Write evaluateRPN(_:) with typed throws, for words separated by spaces.

enum RPNError: Error, Equatable {
    case notEnoughOperands(String)   // the operator that found too few
    case unknownWord(String)
    case divisionByZero
    case leftover(Int)               // how many numbers remained, if not 1
}
Show solution
enum RPNError: Error, Equatable {
    case notEnoughOperands(String)
    case unknownWord(String)
    case divisionByZero
    case leftover(Int)
}

func evaluateRPN(_ text: String) throws(RPNError) -> Int {
    var stack: [Int] = []
    for word in text.split(separator: " ").map(String.init) {
        if let n = Int(word) {
            stack.append(n)
            continue
        }
        guard ["+", "-", "*", "/"].contains(word) else {
            throw .unknownWord(word)
        }
        guard stack.count >= 2 else {
            throw .notEnoughOperands(word)
        }
        let b = stack.removeLast()
        let a = stack.removeLast()
        switch word {
        case "+": stack.append(a + b)
        case "-": stack.append(a - b)
        case "*": stack.append(a * b)
        default:
            guard b != 0 else {
                throw .divisionByZero
            }
            stack.append(a / b)
        }
    }
    guard stack.count == 1 else {
        throw .leftover(stack.count)
    }
    return stack[0]
}

func result(_ text: String) -> Result<Int, RPNError> {
    Result { () throws(RPNError) -> Int in try evaluateRPN(text) }
}

assert(result("3 4 + 2 *") == .success(14))
assert(result("5 1 2 + 4 * + 3 -") == .success(14))
assert(result("10 3 -") == .success(7))
assert(result("1 +") == .failure(.notEnoughOperands("+")))
assert(result("2 x") == .failure(.unknownWord("x")))
assert(result("1 0 /") == .failure(.divisionByZero))
assert(result("1 2") == .failure(.leftover(2)))
assert(result("") == .failure(.leftover(0)))

Note which operand is which: the first number popped is the right operand, so 10 3 - is 10 − 3. Wrapping each evaluation in a Result makes the tests one line each: Result is Equatable when its value and error types are.

Q3: Boolean formulas

Write evaluateFormula(_:), which evaluates formulas made of T, F, ! (not), & (and), | (or), and parentheses, with ! binding tightest and & tighter than |. Spaces may appear anywhere. Use recursive descent, as in Lesson 20’s last lab problem, and throw FormulaError.invalid(at:) with the position of the first character that cannot be understood, or the length of the formula if it ends too early.

formula = conjunction { "|" conjunction }
conjunction = negation { "&" negation }
negation = "!" negation | "T" | "F" | "(" formula ")"
Show solution
enum FormulaError: Error, Equatable {
    case invalid(at: Int)
}

func evaluateFormula(_ text: String) throws(FormulaError) -> Bool {
    let characters = Array(text.filter { $0 != " " })
    var position = 0

    func peek() -> Character? {
        position < characters.count ? characters[position] : nil
    }

    func formula() throws(FormulaError) -> Bool {
        var value = try conjunction()
        while peek() == "|" {
            position += 1
            let right = try conjunction()
            value = value || right
        }
        return value
    }

    func conjunction() throws(FormulaError) -> Bool {
        var value = try negation()
        while peek() == "&" {
            position += 1
            let right = try negation()
            value = value && right
        }
        return value
    }

    func negation() throws(FormulaError) -> Bool {
        guard let c = peek() else {
            throw .invalid(at: position)
        }
        position += 1
        switch c {
        case "!":
            return try !negation()
        case "T":
            return true
        case "F":
            return false
        case "(":
            let value = try formula()
            guard peek() == ")" else {
                throw .invalid(at: position)
            }
            position += 1
            return value
        default:
            throw .invalid(at: position - 1)
        }
    }

    let value = try formula()
    guard position == characters.count else {
        throw .invalid(at: position)
    }
    return value
}

assert(try! evaluateFormula("T & (F | !T)") == false)
assert(try! evaluateFormula("F | T & T") == true)       // & before |
assert(try! evaluateFormula("!!T") == true)
assert(try! evaluateFormula("!(F | F) & T") == true)
assert((try? evaluateFormula("T & ")) == nil)
do {
    _ = try evaluateFormula("T & X")
} catch {
    assert(error == .invalid(at: 2))   // positions ignore spaces: "T&X"
}

Each function evaluates while it parses, so there is no tree: for a language this small, the parser is the interpreter. Note that value || right is computed after right has been parsed, not with ||’s short circuit applied to the parse itself; otherwise T | X would skip over the X without noticing it is invalid.

Q4: Every problem in a file

A configuration file has one key = value setting per line; blank lines and lines starting with # are ignored. Write readConfig(_:), which returns the settings found and a list of problems, each with its line number (counting from 1): a line without =, an empty key, or a key set twice. Use a function that returns a Result for each line.

enum ConfigProblem: Error, Equatable {
    case missingEquals(line: Int)
    case emptyKey(line: Int)
    case duplicate(String, line: Int)
}
Show solution
enum ConfigProblem: Error, Equatable {
    case missingEquals(line: Int)
    case emptyKey(line: Int)
    case duplicate(String, line: Int)
}

func trimmed(_ s: Substring) -> String {
    String(s.drop { $0 == " " }.reversed().drop { $0 == " " }.reversed())
}

func parseLine(_ line: String, number: Int) -> Result<(String, String), ConfigProblem>? {
    let text = trimmed(line[...])
    if text.isEmpty || text.hasPrefix("#") {
        return nil
    }
    guard let equals = text.firstIndex(of: "=") else {
        return .failure(.missingEquals(line: number))
    }
    let key = trimmed(text[..<equals])
    let value = trimmed(text[text.index(after: equals)...])
    guard !key.isEmpty else {
        return .failure(.emptyKey(line: number))
    }
    return .success((key, value))
}

func readConfig(_ text: String) -> (settings: [String: String], problems: [ConfigProblem]) {
    var settings: [String: String] = [:]
    var problems: [ConfigProblem] = []
    let lines = text.split(separator: "\n", omittingEmptySubsequences: false)
    for (index, line) in lines.enumerated() {
        switch parseLine(String(line), number: index + 1) {
        case nil:
            continue
        case .failure(let problem):
            problems.append(problem)
        case .success(let (key, value)):
            if settings[key] != nil {
                problems.append(.duplicate(key, line: index + 1))
            } else {
                settings[key] = value
            }
        }
    }
    return (settings, problems)
}

let file = """
# display
theme = dark
font size = 14

width
= 80
theme = light
"""
let config = readConfig(file)
assert(config.settings == ["theme": "dark", "font size": "14"])
assert(config.problems == [.missingEquals(line: 5), .emptyKey(line: 6), .duplicate("theme", line: 7)])

parseLine returns an optional Result: nil for lines with nothing in them, and otherwise success or failure. The switch in readConfig matches all three with patterns, as Lesson 19 showed for optionals. The duplicate check needs all the lines before it, so it belongs in readConfig, not in parseLine, which sees one line at a time.

Q5 (optional): A tiny Forth

Forth is a stack language, like Q2’s calculator, in which programs can define new words. Write runForth(_:), which returns the stack at the end. Support numbers; +, -, *; dup (copy the top), drop (remove the top), swap (exchange the top two); and definitions: : name body… ; defines name so that using it runs the body. A word used before it is defined, or an operation on too small a stack, throws.

Show solution
enum ForthError: Error, Equatable {
    case unknownWord(String)
    case stackUnderflow(String)
    case unfinishedDefinition
}

func runForth(_ program: String) throws(ForthError) -> [Int] {
    var stack: [Int] = []
    var definitions: [String: [String]] = [:]

    func pop(_ word: String, _ count: Int) throws(ForthError) -> [Int] {
        guard stack.count >= count else {
            throw .stackUnderflow(word)
        }
        let top = Array(stack.suffix(count))
        stack.removeLast(count)
        return top
    }

    func execute(_ words: [String]) throws(ForthError) {
        var index = 0
        while index < words.count {
            let word = words[index]
            index += 1
            if let n = Int(word) {
                stack.append(n)
            } else if word == ":" {
                guard let end = words[index...].firstIndex(of: ";"), end > index else {
                    throw .unfinishedDefinition
                }
                definitions[words[index]] = Array(words[(index + 1)..<end])
                index = end + 1
            } else if let body = definitions[word] {
                try execute(body)
            } else {
                switch word {
                case "+": let v = try pop(word, 2); stack.append(v[0] + v[1])
                case "-": let v = try pop(word, 2); stack.append(v[0] - v[1])
                case "*": let v = try pop(word, 2); stack.append(v[0] * v[1])
                case "dup": let v = try pop(word, 1); stack += [v[0], v[0]]
                case "drop": _ = try pop(word, 1)
                case "swap": let v = try pop(word, 2); stack += [v[1], v[0]]
                default: throw .unknownWord(word)
                }
            }
        }
    }

    try execute(program.split(separator: " ").map(String.init))
    return stack
}

assert(try! runForth("1 2 3 + *") == [5])
assert(try! runForth(": square dup * ; 7 square") == [49])
assert(try! runForth(": square dup * ; : fourth square square ; 3 fourth") == [81])
assert(try! runForth("1 2 swap drop") == [2])
assert((try? runForth("1 +")) == nil)
assert((try? runForth("foo")) == nil)
assert((try? runForth(": broken 1 2")) == nil)

Definitions are stored as lists of words, and running a defined word runs its body with the same execute function, recursively. The dictionary is an environment with a single frame, and a definition may use words defined before it, as fourth uses square. Checking definitions[word] before the built-in words means a program could even redefine dup.