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

Recursion

Functions that call themselves, the recursive leap of faith, the order in which recursive calls print, and mutual recursion.

CS61A
Recursion · Composing Programs 1.7
Swift book
Functions

A function is recursive when its body calls the function itself. That sounds circular, but it works as long as each call works on a smaller problem, and the smallest problems are answered directly.

The anatomy of a recursive function

Here is the sum of digits from Lab 2, written recursively:

func sumDigits(_ n: Int) -> Int {
    if n < 10 {
        return n                        // base case
    }
    return n % 10 + sumDigits(n / 10)   // recursive case
}

print(sumDigits(2026))   // 10

Every recursive function has the same parts:

  1. Base cases: inputs small enough to answer without recursion. A one-digit number is its own digit sum.
  2. Recursive cases: break the problem into a smaller version of itself, call the function on it, and use the result. The digit sum of 2026 is 6 plus the digit sum of 202.

The recursive leap of faith

How do you know sumDigits(202) is right while you are still writing sumDigits? CS61A’s answer: trust it. Check the base case, check that the recursive call is on a smaller input, and check that you use its result correctly assuming it is right. If all three hold, induction does the rest.

The same reasoning gives the recursive factorial. n! = n × (n − 1)!, and 0! = 1:

func factorial(_ n: Int) -> Int {
    n == 0 ? 1 : n * factorial(n - 1)
}
print(factorial(5))   // 120

What would Swift print?

func total(_ n: Int) -> Int {
    n == 0 ? 0 : n + total(n - 1)
}
print(total(4))

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

Show answer and explanation

Answer10

total(4) is 4 + total(3), which is 4 + 3 + total(2), and so on down to total(0), which is 0. The result is 4 + 3 + 2 + 1 + 0 = 10.

Without a base case the calls never stop. Each call takes a little memory on the call stack, and eventually it runs out.

What would Swift print?

func countdown(_ n: Int) -> Int {
    countdown(n - 1)
}
print(countdown(3))

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

Show answer and explanation

AnswerError

There is no base case, so countdown calls itself forever. Swift warns that “function call causes an infinite recursion”, and at run time the program crashes with a stack overflow.

Order of recursive calls

When a recursive call happens in the middle of a function body, the rest of the body waits until it returns. CS61A’s cascade shows this clearly:

func cascade(_ n: Int) {
    print(n)
    if n >= 10 {
        cascade(n / 10)
        print(n)
    }
}
cascade(123)

What would Swift print?

func cascade(_ n: Int) {
    print(n)
    if n >= 10 {
        cascade(n / 10)
        print(n)
    }
}
cascade(123)

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

Show answer and explanation

Answer123\n12\n1\n12\n123

cascade(123) prints 123, then calls cascade(12), which prints 12 and calls cascade(1). That call prints 1 and returns without recursing. Then cascade(12) finishes by printing 12 again, and finally cascade(123) prints 123 again.

Each call has its own frame with its own n. While cascade(1) runs, the frames for 12 and 123 are still waiting, each holding its own value.

Mutual recursion

Two functions can call each other. This pair decides whether a non-negative number is even or odd, using only subtraction:

func isEven(_ n: Int) -> Bool {
    n == 0 ? true : isOdd(n - 1)
}
func isOdd(_ n: Int) -> Bool {
    n == 0 ? false : isEven(n - 1)
}
print(isEven(10), isOdd(7), isEven(3))   // true true false

Top-level functions in a Swift file can refer to each other in any order, so isEven can call isOdd before isOdd is written.

A real one: the Luhn algorithm

Credit card numbers end in a check digit computed by the Luhn algorithm. Starting from the rightmost digit and moving left, every second digit is doubled (and if doubling gives a two-digit number, its digits are added). The sum of all the resulting digits is a multiple of 10 for a valid number.

Two mutually recursive functions express “every second digit” directly: one handles a digit that is kept as is, the other a digit that is doubled, and each passes the rest of the number to the other.

func sumDigits(_ n: Int) -> Int {
    n < 10 ? n : n % 10 + sumDigits(n / 10)
}

func luhnSum(_ n: Int) -> Int {          // the last digit is kept
    n < 10 ? n : luhnSumDoubled(n / 10) + n % 10
}

func luhnSumDoubled(_ n: Int) -> Int {   // the last digit is doubled
    let doubled = sumDigits(n % 10 * 2)
    return n < 10 ? doubled : luhnSum(n / 10) + doubled
}

print(luhnSum(138743))                        // 30
print(luhnSum(5105105105105100) % 10 == 0)    // true: a valid test card number

Iteration and recursion

Any loop can be rewritten as recursion: the loop’s changing variables become parameters, and the loop condition becomes the base case. Here is the same sum twice:

func sumTo(_ n: Int) -> Int {        // iterative
    var total = 0
    var k = 1
    while k <= n {
        total += k
        k += 1
    }
    return total
}

func sumTo(_ n: Int, from k: Int = 1, total: Int = 0) -> Int {   // recursive
    k > n ? total : sumTo(n, from: k + 1, total: total + k)
}

print(sumTo(100), sumTo(100, from: 1))   // 5050 5050

The recursive version names the loop’s state (k and total) as parameters with defaults, so callers still write sumTo(100). Going the other way, from recursion to a loop, can take more work when the recursion makes several calls, as the next lesson shows.

Put the lines in order

Put the lines in order: a recursive digit sum that prints 10.

  1. if n < 10 {
  2. print(sumDigits(2026))
  3. return n % 10 + sumDigits(n / 10)
  4. func sumDigits(_ n: Int) -> Int {
  5. }
  6. }
  7. return n

Show the correct program
func sumDigits(_ n: Int) -> Int {
    if n < 10 {
        return n
    }
    return n % 10 + sumDigits(n / 10)
}
print(sumDigits(2026))

Lab 6: Recursion

Solve these without loops.

Q0: What would Swift print?

What would Swift print?

func f(_ n: Int) -> Int {
    if n <= 1 {
        return 1
    }
    return f(n - 2) + 1
}
print(f(6), f(7))

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

Show answer and explanation

Answer4 4

f(6) goes 6, 4, 2, 0: three recursive steps adding 1 each to the base value 1. f(7) goes 7, 5, 3, 1, also three steps.

What would Swift print?

func show(_ n: Int) {
    if n == 0 {
        return
    }
    show(n - 1)
    print(n, terminator: " ")
}
show(4)
print()

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

Show answer and explanation

Answer1 2 3 4

The recursive call comes before the print, so each call waits for the smaller ones to finish printing first. The numbers come out in increasing order.

What would Swift print?

func isEven(_ n: Int) -> Bool { n == 0 ? true : isOdd(n - 1) }
func isOdd(_ n: Int) -> Bool { n == 0 ? false : isEven(n - 1) }
print(isOdd(9), isEven(-2))

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

Show answer and explanation

AnswerError

isOdd(9) is fine, but isEven(-2) counts down from −2 and never reaches 0, so the calls never stop and the program crashes. The base case only covers non-negative inputs.

Q1: Count the eights

Return the number of times the digit 8 appears in a non-negative integer.

func numEights(_ n: Int) -> Int {
    // your code here
}
Show solution
func numEights(_ n: Int) -> Int {
    if n == 0 {
        return 0
    }
    let last = n % 10 == 8 ? 1 : 0
    return last + numEights(n / 10)
}

assert(numEights(3) == 0)
assert(numEights(8) == 1)
assert(numEights(88888888) == 8)
assert(numEights(2638) == 1)
assert(numEights(86380) == 2)
assert(numEights(12345) == 0)

The last digit contributes 0 or 1, and the rest of the number is a smaller instance of the same problem.

Q2: Hailstone

Starting from a positive integer n: if it is even, divide it by 2; otherwise multiply by 3 and add 1. Repeat until you reach 1. Write hailstone(n), which prints every number in the sequence and returns how many numbers were printed.

func hailstone(_ n: Int) -> Int {
    // your code here
}
Show solution
func hailstone(_ n: Int) -> Int {
    print(n)
    if n == 1 {
        return 1
    }
    let next = n % 2 == 0 ? n / 2 : 3 * n + 1
    return 1 + hailstone(next)
}

let steps = hailstone(10)   // prints 10 5 16 8 4 2 1, one per line
assert(steps == 7)
assert(hailstone(1) == 1)

Nobody has proved that the sequence reaches 1 for every starting number: this is the Collatz conjecture. It has been checked for every starting number anyone has tried.

Q3: Is it prime?

Write isPrime(n) using a helper function defined inside it, which checks candidate divisors starting from 2.

func isPrime(_ n: Int) -> Bool {
    // your code here
}
Show solution
func isPrime(_ n: Int) -> Bool {
    func noDivisorFrom(_ k: Int) -> Bool {
        if k * k > n {
            return true
        }
        if n % k == 0 {
            return false
        }
        return noDivisorFrom(k + 1)
    }
    return n > 1 && noDivisorFrom(2)
}

assert(!isPrime(1))
assert(isPrime(2))
assert(isPrime(13))
assert(!isPrime(91))   // 7 * 13
assert((1...20).filter(isPrime) == [2, 3, 5, 7, 11, 13, 17, 19])

The helper needs an extra parameter, the next candidate k, that the original problem does not have. Defining it inside isPrime lets it see n without passing it along. Stopping once k² > n works because any divisor larger than √n pairs with one smaller than it.

Q4: Interleaved sum

Write interleavedSum(_:_:_:), which returns odd(1) + even(2) + odd(3) + … up to n, applying the function odd to odd numbers and even to even ones. Use recursion with a helper, and do not test whether numbers are odd with %.

func interleavedSum(_ n: Int, _ odd: (Int) -> Int, _ even: (Int) -> Int) -> Int {
    // your code here
}
Show solution
func interleavedSum(_ n: Int, _ odd: (Int) -> Int, _ even: (Int) -> Int) -> Int {
    func sum(from k: Int, useOdd: Bool) -> Int {
        if k > n {
            return 0
        }
        let term = useOdd ? odd(k) : even(k)
        return term + sum(from: k + 1, useOdd: !useOdd)
    }
    return sum(from: 1, useOdd: true)
}

assert(interleavedSum(5, { $0 }, { $0 * $0 }) == 29)   // 1 + 4 + 3 + 16 + 5
assert(interleavedSum(1, { $0 }, { $0 * 10 }) == 1)
assert(interleavedSum(0, { $0 }, { $0 }) == 0)

The flag useOdd flips on every call, so the helper always knows which function applies without doing any arithmetic.

Q5: Ping-pong

The ping-pong sequence counts up from 1 and switches direction every time the step number k is a multiple of 8 or contains the digit 8. The first terms are 1, 2, 3, 4, 5, 6, 7, 8 (step 8: switch), 7, 6, 5, 4, 3, 2, 1, 0 (step 16: switch), 1, 2, 3, … Write pingPong(_:), the nth element, with recursion and no assignment statements.

func pingPong(_ n: Int) -> Int {
    // your code here
}
Show solution
func containsEight(_ k: Int) -> Bool {
    k == 0 ? false : (k % 10 == 8 || containsEight(k / 10))
}

func pingPong(_ n: Int) -> Int {
    func step(_ k: Int, value: Int, direction: Int) -> Int {
        if k == n {
            return value
        }
        let switches = k % 8 == 0 || containsEight(k)
        let next = switches ? -direction : direction
        return step(k + 1, value: value + next, direction: next)
    }
    return step(1, value: 1, direction: 1)
}

assert(pingPong(8) == 8)
assert(pingPong(10) == 6)
assert(pingPong(15) == 1)
assert(pingPong(21) == -1)
assert(pingPong(30) == -2)
assert(pingPong(68) == 0)
assert(pingPong(69) == -1)
assert(pingPong(80) == 0)
assert(pingPong(81) == 1)
assert(pingPong(82) == 0)
assert(pingPong(100) == -6)

The helper carries the state a loop would keep (the step, the value, and the direction) as parameters, as in the section on iteration and recursion.

Q6 (optional): Missing digits

Given a number whose digits are in non-decreasing order, missingDigits(_:) returns how many digits are missing between its smallest and largest digit. missingDigits(1248) is 4 (3, 5, 6, and 7 are missing).

Show solution
func missingDigits(_ n: Int) -> Int {
    if n < 10 {
        return 0
    }
    let last = n % 10
    let rest = n / 10
    let gap = max(0, last - rest % 10 - 1)
    return gap + missingDigits(rest)
}

assert(missingDigits(1248) == 4)
assert(missingDigits(19) == 7)
assert(missingDigits(1122) == 0)
assert(missingDigits(123456) == 0)
assert(missingDigits(3558) == 3)
assert(missingDigits(35578) == 2)
assert(missingDigits(4) == 0)

Each step compares the last two digits: the gap between them counts missing digits, and max(0, …) handles repeated digits, whose gap would be −1.

What’s next

Next lesson: tree recursion, where a function makes more than one recursive call.