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

Higher-order functions

Function types, functions as arguments and return values, closure expressions, and the map, filter, and reduce that Swift builds in.

CS61A
Higher-Order Functions · Composing Programs 1.6
Swift book
Functions · Closures

Here are three functions that look almost the same:

func sumNaturals(_ n: Int) -> Int {
    var total = 0
    for k in 1...n { total += k }
    return total
}
func sumCubes(_ n: Int) -> Int {
    var total = 0
    for k in 1...n { total += k * k * k }
    return total
}
func sumSquares(_ n: Int) -> Int {
    var total = 0
    for k in 1...n { total += k * k }
    return total
}
print(sumNaturals(5), sumCubes(5), sumSquares(5))   // 15 225 55

They differ only in what is added for each k. CS61A’s answer is to make that difference a parameter. The parameter is not a number but a function. A function that takes or returns a function is a higher-order function.

Function types

Every function has a type written from its parameters and result. square below has type (Int) -> Int: it takes one Int and returns an Int. Functions are values, so they can be bound to names like any other value:

func square(_ x: Int) -> Int { x * x }

let f: (Int) -> Int = square
print(f(7))   // 49

Note there are no parentheses after square on the second line. square is the function itself; square(7) would call it.

Functions as arguments

Now the three sums collapse into one:

func summation(_ n: Int, _ term: (Int) -> Int) -> Int {
    var total = 0
    for k in 1...n {
        total += term(k)
    }
    return total
}

func cube(_ x: Int) -> Int { x * x * x }

print(summation(5, cube))   // 225

summation knows how to add things up; cube knows what to add. Neither has to know about the other’s job.

Closure expressions

Naming a tiny function just to pass it once is clumsy. A closure expression writes a function inline. The full form spells out the types, then in, then the body:

func summation(_ n: Int, _ term: (Int) -> Int) -> Int {
    var total = 0
    for k in 1...n { total += term(k) }
    return total
}

print(summation(5, { (k: Int) -> Int in return k * k }))
print(summation(5, { k in k * k }))      // types inferred
print(summation(5, { $0 * $0 }))         // shorthand argument names
print(summation(5) { $0 * $0 })          // trailing closure

All four lines print 55. Swift can infer the closure’s types from summation’s parameter, a single-expression body returns its value, and $0 names the first argument. When the closure is the last argument, it can be written after the parentheses as a trailing closure.

What would Swift print?

let twice = { (x: Int) in x * 2 }
print(twice(twice(3)))

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

Show answer and explanation

Answer12

twice is bound to a closure. twice(3) is 6, and twice(6) is 12.

Functions as return values

A function can build and return a new function:

func makeAdder(_ n: Int) -> (Int) -> Int {
    return { x in x + n }
}

let addThree = makeAdder(3)
print(addThree(4))        // 7
print(makeAdder(10)(1))   // 11

The return type (Int) -> Int says makeAdder gives back a function. The closure it returns uses n, a parameter of makeAdder, even after makeAdder has returned. How that works is next lesson’s topic.

What would Swift print?

func makeAdder(_ n: Int) -> (Int) -> Int {
    return { x in x + n }
}
let addTwo = makeAdder(2)
print(addTwo(addTwo(1)), makeAdder(5)(0))

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

Show answer and explanation

Answer5 5

addTwo(1) is 3 and addTwo(3) is 5. makeAdder(5) returns a function that adds 5, and calling it on 0 gives 5.

A closure that is stored or returned, and so may run after the function receiving it has returned, must be marked @escaping. Swift requires the mark so that you notice when a function holds onto one.

Put the lines in order

Put the lines in order. compose(f, g) should return a function that applies g and then f; the program prints 12.

  1. print(incrementThenDouble(5))
  2. return { x in
  3. f(g(x))
  4. func compose(_ f: @escaping (Int) -> Int, _ g: @escaping (Int) -> Int) -> (Int) -> Int {
  5. }
  6. let incrementThenDouble = compose({ $0 * 2 }, { $0 + 1 })
  7. }

Show the correct program
func compose(_ f: @escaping (Int) -> Int, _ g: @escaping (Int) -> Int) -> (Int) -> Int {
    return { x in
        f(g(x))
    }
}
let incrementThenDouble = compose({ $0 * 2 }, { $0 + 1 })
print(incrementThenDouble(5))

map, filter, and reduce

Swift’s collections come with higher-order functions built in. map applies a function to every element, filter keeps the elements for which a function returns true, and reduce combines everything into one value:

let numbers = [1, 2, 3, 4, 5]
print(numbers.map { $0 * $0 })          // [1, 4, 9, 16, 25]
print(numbers.filter { $0 % 2 == 1 })   // [1, 3, 5]
print(numbers.reduce(0, +))             // 15

reduce(0, +) starts from 0 and combines with +. Operators are functions, so + can be passed wherever a (Int, Int) -> Int is expected.

What would Swift print?

print([1, 2, 3, 4].filter { $0 % 2 == 0 }.map { $0 * 10 })
print([1, 2, 3].reduce(1, *))

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

Show answer and explanation

Answer[20, 40]\n6

filter keeps [2, 4], then map multiplies each by 10. reduce(1, *) multiplies 1 × 1 × 2 × 3 = 6.

More from the standard library

Many everyday questions about a collection are higher-order functions that take a predicate, a function returning Bool:

let scores = [72, 95, 88, 61]
print(scores.sorted(by: >))                  // [95, 88, 72, 61]
print(scores.contains(where: { $0 > 90 }))   // true
print(scores.allSatisfy { $0 >= 60 })        // true
print(scores.first(where: { $0 > 80 })!)     // 95

sorted(by: >) passes the > operator as the comparison, so the largest come first. first(where:) may find nothing, so it returns an optional; Lesson 11 explains the !.

Functions that return functions that return functions

Nothing stops the pattern at one level. makeAdder returned a function; this returns a function that returns a function, one argument at a time:

func makeLinear(_ slope: Int) -> (Int) -> (Int) -> Int {
    return { intercept in
        return { x in slope * x + intercept }
    }
}
let line = makeLinear(2)(1)   // y = 2x + 1
print(line(3), makeLinear(-1)(10)(4))   // 7 6

Supplying arguments one at a time like this is called currying; Lesson 5 builds a function that curries any two-argument function.

Lab 3: Higher-order functions

Q0: What would Swift print?

What would Swift print?

func apply(_ f: (Int) -> Int, twiceTo x: Int) -> Int {
    f(f(x))
}
print(apply({ $0 + 3 }, twiceTo: 1), apply({ $0 * $0 }, twiceTo: 3))

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

Show answer and explanation

Answer7 81

apply calls f on the result of f. Adding 3 twice to 1 gives 7; squaring 3 twice gives 9, then 81.

What would Swift print?

let square = { (x: Int) in x * x }
let numbers = [3, 1, 2]
print(numbers.map(square).sorted(), numbers.sorted(by: >).map { $0 - 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, 4, 9] [2, 1, 0]

The first expression squares then sorts ascending. The second sorts descending, [3, 2, 1], then subtracts 1 from each.

What would Swift print?

func makeMultiplier(_ n: Int) -> (Int) -> Int {
    return { $0 * n }
}
let triple = makeMultiplier(3)
print(triple(makeMultiplier(2)(5)))

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

Show answer and explanation

Answer30

makeMultiplier(2)(5) builds a doubling function and applies it to 5, giving 10. triple(10) is 30.

Q1: Product

Write product(n, term), which returns term(1) * term(2) * … * term(n).

func product(_ n: Int, _ term: (Int) -> Int) -> Int {
    // your code here
}
Show solution
func product(_ n: Int, _ term: (Int) -> Int) -> Int {
    var total = 1
    for k in 1...n {
        total *= term(k)
    }
    return total
}

assert(product(3, { $0 }) == 6)          // 1 * 2 * 3
assert(product(5, { $0 }) == 120)        // 5 factorial
assert(product(3, { $0 * $0 }) == 36)    // 1 * 4 * 9
assert(product(1, { $0 * 7 }) == 7)

Q2: Accumulate

summation and product share a pattern too. Write accumulate(merger, start, n, term), which merges start with term(1), …, term(n) using the two-argument function merger. Then define summation and product in one line each using accumulate.

func accumulate(_ merger: (Int, Int) -> Int, _ start: Int, _ n: Int, _ term: (Int) -> Int) -> Int {
    // your code here
}
Show solution
func accumulate(_ merger: (Int, Int) -> Int, _ start: Int, _ n: Int, _ term: (Int) -> Int) -> Int {
    var total = start
    for k in 1...n {
        total = merger(total, term(k))
    }
    return total
}

func summation(_ n: Int, _ term: (Int) -> Int) -> Int { accumulate(+, 0, n, term) }
func product(_ n: Int, _ term: (Int) -> Int) -> Int { accumulate(*, 1, n, term) }

assert(accumulate(+, 0, 5, { $0 }) == 15)
assert(accumulate(+, 11, 5, { $0 }) == 26)
assert(accumulate(*, 2, 3, { $0 * $0 }) == 72)   // 2 * 1 * 4 * 9
assert(summation(5, { $0 * $0 * $0 }) == 225)
assert(product(5, { $0 }) == 120)

Q3: Make a repeater

Write makeRepeater(f, n), which returns a function that applies f to its argument n times. When n is 0, the returned function should return its argument unchanged.

func makeRepeater(_ f: @escaping (Int) -> Int, _ n: Int) -> (Int) -> Int {
    // your code here
}
Show solution
func makeRepeater(_ f: @escaping (Int) -> Int, _ n: Int) -> (Int) -> Int {
    return { x in
        var result = x
        for _ in 0..<n {
            result = f(result)
        }
        return result
    }
}

assert(makeRepeater({ $0 + 1 }, 3)(5) == 8)
assert(makeRepeater({ $0 * 3 }, 5)(1) == 243)
assert(makeRepeater({ $0 * $0 }, 2)(5) == 625)
assert(makeRepeater({ $0 * 3 }, 0)(5) == 5)

f is used inside the returned closure, which outlives the call to makeRepeater, so the parameter must be @escaping.

Q4: Cycle

Write cycle(_:_:_:), which takes three functions and returns a function f(n). f(n) in turn returns a function that applies the three functions in rotation, n applications in total: first f1, then f2, then f3, then f1 again, and so on. With n of 0 it returns its argument unchanged.

func cycle(_ f1: @escaping (Int) -> Int, _ f2: @escaping (Int) -> Int,
           _ f3: @escaping (Int) -> Int) -> (Int) -> (Int) -> Int {
    // your code here
}
Show solution
func cycle(_ f1: @escaping (Int) -> Int, _ f2: @escaping (Int) -> Int,
           _ f3: @escaping (Int) -> Int) -> (Int) -> (Int) -> Int {
    return { n in
        return { x in
            var result = x
            for step in 0..<n {
                switch step % 3 {
                case 0: result = f1(result)
                case 1: result = f2(result)
                default: result = f3(result)
                }
            }
            return result
        }
    }
}

let addOne: (Int) -> Int = { $0 + 1 }
let double: (Int) -> Int = { $0 * 2 }
let addThree: (Int) -> Int = { $0 + 3 }
let myCycle = cycle(addOne, double, addThree)
assert(myCycle(0)(5) == 5)
assert(myCycle(2)(1) == 4)    // (1 + 1) * 2
assert(myCycle(3)(2) == 9)    // (2 + 1) * 2 + 3
assert(myCycle(4)(2) == 10)
assert(myCycle(6)(1) == 19)

step % 3 picks which function applies at each step; the three functions and n all come from enclosing closures.

Q5: Counting with a condition

Write countCond(_:), which takes a two-argument predicate condition and returns a function of n that counts the integers i from 1 to n for which condition(n, i) is true. Then use it to define countFactors and countPrimes in one line each.

func countCond(_ condition: @escaping (Int, Int) -> Bool) -> (Int) -> Int {
    // your code here
}
Show solution
func countCond(_ condition: @escaping (Int, Int) -> Bool) -> (Int) -> Int {
    return { n in
        var count = 0
        for i in 1...n where condition(n, i) {
            count += 1
        }
        return count
    }
}

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

let countFactors = countCond { n, i in n % i == 0 }
let countPrimes = countCond { _, i in isPrime(i) }

assert(countFactors(2) == 2)    // 1, 2
assert(countFactors(12) == 6)   // 1, 2, 3, 4, 6, 12
assert(countPrimes(12) == 5)    // 2, 3, 5, 7, 11
assert(countPrimes(20) == 8)

countPrimes’s condition ignores n, which is why it names that parameter _. The same counting loop serves both questions.

Q6 (optional): Compose them all

Write composeAll(_:), which takes an array of functions and returns their composition: applying the first, then the second, and so on. An empty array gives the identity function. Use reduce, no loops.

Show solution
func composeAll(_ functions: [(Int) -> Int]) -> (Int) -> Int {
    functions.reduce({ $0 }) { composed, next in
        { x in next(composed(x)) }
    }
}

let steps: [(Int) -> Int] = [{ $0 + 1 }, { $0 * 2 }, { $0 + 3 }]
assert(composeAll(steps)(5) == 15)   // (5 + 1) * 2 + 3
assert(composeAll([])(5) == 5)

reduce starts from the identity function and, for each function in the array, builds a new closure that runs everything so far and then the next one. The result is a function built out of functions, one closure per step.

What’s next

Next lesson: how a returned closure still sees the names around it, using environments, frames, and captured values.