---
title: "Functional Programming"
book: "University Computer Science — Year 2"
subject: computer-science
language: en
chapter: 9
exercises: 12
source: https://one-course.com/books/computer-science/4/en/chapter/9-functional-programming
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 9 — Functional Programming

The sum of the squares of the odd readings, written twice: as a loop that changes a variable, and as one expression that says what is computed.

```rust
    let readings = [12, 7, 3, 20, 9, 4, 15];

    let mut total = 0;
    for r in readings {
        if r % 2 == 1 {
            total += r * r;
        }
    }

    let total2: i32 = readings.iter().filter(|&&r| r % 2 == 1).map(|r| r * r).sum();
    println!("{total} {total2}");
}
```

***Listing 9.1.** A loop and a pipeline code/bachelor-2/09-functional-programming/listings/odd_squares.rs*

```
$ rustc --edition 2021 -O -o odd_squares odd_squares.rs && ./odd_squares
364 364
```

***Output 9.1.** $7^2 + 3^2 + 9^2 + 15^2 = 364$, twice.*

The second form reads like a spreadsheet formula, *sum the squares of the odd cells*: no counter, no variable that changes, no order of steps to follow. Functional programming builds programs from such expressions, functions passed to functions, and data that is never modified. This chapter shows the ideas in Rust, which borrows them freely, and what each costs.

**You already know.**

Book 2: a recursive function calls itself on a smaller input, and each pending call occupies a frame of the stack. Book 3: lists and trees are inductive sets, and a property of all of them is proved by structural induction. Chapters [6](https://one-course.com/books/computer-science/4/en/chapter/6-rust-ownership-and-borrowing#ch-b2-rust-ownership), [7](https://one-course.com/books/computer-science/4/en/chapter/7-enums-pattern-matching-and-error-handling#ch-b2-rust-enums-and-errors) and [8](https://one-course.com/books/computer-science/4/en/chapter/8-traits-and-generics#ch-b2-rust-traits-and-generics): [ownership](https://one-course.com/books/computer-science/4/en/chapter/6-rust-ownership-and-borrowing#def-b2-rust-ownership-ownership) and borrowing, recursive enums with `Box`, [traits](https://one-course.com/books/computer-science/4/en/chapter/8-traits-and-generics#def-b2-rust-traits-and-generics-trait) and [trait objects](https://one-course.com/books/computer-science/4/en/chapter/8-traits-and-generics#def-b2-rust-traits-and-generics-trait-object).

## 9.1 Functions as values

**Definition 9.1 (First-class function, higher-order function).**

Functions are *first-class* in a language if they are values: stored in variables and data structures, passed as arguments, returned as results. A *higher-order function* takes a function as argument or returns one.

**Definition 9.2 (Closure, captured environment).**

A *closure* is a function value written inline, `|x| x * rate`, that may use variables of the scope where it is written. Those variables form its *captured environment*: the closure stores a reference to each, a mutable reference, or the value itself (`move`). By what its body does with them, a Rust closure implements `Fn` (it only reads them, and may be called any number of times), `FnMut` (it modifies them: called through a mutable [borrow](https://one-course.com/books/computer-science/4/en/chapter/6-rust-ownership-and-borrowing#def-b2-rust-ownership-borrow)), or only `FnOnce` (it gives a captured value away: callable once).

```rust
fn apply_twice(f: impl Fn(u32) -> u32, x: u32) -> u32 {
    f(f(x))
}

fn make_fine(cents_per_day: u32, grace: u32) -> impl Fn(u32) -> u32 {
    // move: the closure owns its copies of the two numbers, and outlives this call
    move |days| days.saturating_sub(grace) * cents_per_day
}

fn main() {
    let rate = 10;
    let fine = |days: u32| days * rate; // borrows rate: Fn
    println!("{} {}", fine(4), apply_twice(fine, 3));

    let mut calls = 0;
    let mut count = || calls += 1; // borrows calls mutably: FnMut
    count();
    count();
    println!("calls {calls}");

    let title = String::from("Seven Comets");
    let give = move || title; // moves title in, and gives it away when called: FnOnce
    let t = give();
    println!("{t}");

    let fines: Vec<Box<dyn Fn(u32) -> u32>> =
        vec![Box::new(make_fine(10, 21)), Box::new(make_fine(25, 14))];
    println!("{:?}", fines.iter().map(|f| f(30)).collect::<Vec<_>>());
}
```

***Listing 9.2.** Three kinds of capture, and [closures](#def-b2-functional-programming-closure) returned code/bachelor-2/09-functional-programming/listings/closures.rs*

```
$ rustc --edition 2021 -O -o closures closures.rs && ./closures
40 300
calls 2
Seven Comets
[90, 400]
```

***Output 9.2.** The fines of 30 days with 21 and 14 days of grace.*

`make_fine` returns a [closure](#def-b2-functional-programming-closure): its parameters die with the call, so the [closure](#def-b2-functional-programming-closure) must own copies, hence `move`. Each [closure](#def-b2-functional-programming-closure) has its own anonymous type, which is why `make_fine` declares its result as `impl Fn(u32) -> u32`, and why [closures](#def-b2-functional-programming-closure) of different bodies can share a vector only as `Box<dyn Fn>`, [trait objects](https://one-course.com/books/computer-science/4/en/chapter/8-traits-and-generics#def-b2-rust-traits-and-generics-trait-object) ([Chapter 8](https://one-course.com/books/computer-science/4/en/chapter/8-traits-and-generics#ch-b2-rust-traits-and-generics)). A [closure](#def-b2-functional-programming-closure) that gives its capture away cannot run twice:

```
error[E0382]: use of moved value: `give`
 --> fn_once_error.rs:7:13
  |
6 |     let a = give();
  |             ------ `give` moved due to this call
7 |     let b = give();
  |
note: closure cannot be invoked more than once because it moves the variable `title` out of its environment
 --> fn_once_error.rs:5:24
  |
5 |     let give = move || title;
```

***Output 9.3.** `fn_once_error.rs` calls `give` twice. Some lines are left out.*

![A closure is a struct of its captures plus a function that receives that struct. The first two hold references into main’s frame and may not outlive it; the third holds its own copies.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-functional-programming/fig-54bea2e7577f.svg)

*A [closure](#def-b2-functional-programming-closure) is a struct of its captures plus a function that receives that struct. The first two hold references into `main`’s frame and may not outlive it; the third holds its own copies.*

## 9.2 Map, filter, fold and lazy iterators

**Definition 9.3 (Map operation, filter, fold).**

On a sequence $[x_1, \dots, x_n]$, the *map operation* with a function $f$ gives $[f(x_1),
\dots, f(x_n)]$; the *filter* with a predicate $p$ keeps the $x_i$ with $p(x_i)$ true, in order; the *fold* from $z$ with a two-argument function $g$ gives $g(\dots g(g(z, x_1), x_2) \dots, x_n)$ (a left fold; the right fold is $g(x_1, g(x_2, \dots g(x_n, z)))$). Sums, counts, maxima, and the building of collections are folds.

**Definition 9.4 (Lazy iterator, iterator adaptor).**

A Rust iterator is *lazy*: it computes the next element only when `next` is called. An *iterator adaptor* (`map`, `filter`, `take`, …) wraps an iterator into a new one and does no work when created; a consumer (`sum`, `collect`, `count`, a `for` loop) calls `next` until the end or until it has enough.

```rust
    let pages = [65, 133, 412, 98, 251, 320];
    let it = pages
        .iter()
        .map(|p| {
            println!("  map {p}");
            p * 2
        })
        .filter(|d| {
            println!("  filter {d}");
            *d > 300
        });
    println!("nothing has run yet");
    let first_two: Vec<i32> = it.take(2).collect(); // the consumer pulls, one at a time
    println!("{first_two:?}");
```

***Listing 9.3.** [Side effects](#def-b2-functional-programming-pure) that show when each step runs code/bachelor-2/09-functional-programming/listings/lazy.rs*

```
$ rustc --edition 2021 -O -o lazy lazy.rs && ./lazy
nothing has run yet
  map 65
  filter 130
  map 133
  filter 266
  map 412
  filter 824
  map 98
  filter 196
  map 251
  filter 502
[824, 502]
```

***Output 9.4.** One element at a time, and the last page count is never read.*

![A lazy pipeline is pulled by its consumer. collect asks take for an element, which asks filter, which asks map until one passes; after two, take stops asking, and 320 is never mapped.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-functional-programming/fig-35c5f52175cc.svg)

*A [lazy](#def-b2-functional-programming-lazy) pipeline is pulled by its consumer. `collect` asks `take` for an element, which asks `filter`, which asks `map` until one passes; after two, `take` stops asking, and 320 is never mapped.*

Laziness makes infinite sequences usable, as long as the consumer stops:

```rust
    let squares: Vec<u64> = (1..).map(|n| n * n).take_while(|&s| s < 100).collect();
    println!("{squares:?}");

    // the Fibonacci numbers, each pair made from the previous one
    let pairs = std::iter::successors(Some((0u64, 1u64)), |&(a, b)| Some((b, a + b)));
    let fib = pairs.map(|(a, _)| a);
    println!("{:?}", fib.clone().take(12).collect::<Vec<_>>());
    println!("first above a million: {:?}", fib.clone().find(|&f| f > 1_000_000));

    // the stopping times of a 3n + 1 walk: generated until it reaches 1
    let walk = std::iter::successors(Some(27u64), |&n| {
        if n == 1 { None } else if n % 2 == 0 { Some(n / 2) } else { Some(3 * n + 1) }
    });
    let steps = walk.clone().count() - 1;
    println!("27 reaches 1 after {steps} steps, peaking at {}", walk.max().unwrap());
```

***Listing 9.4.** Three infinite iterators code/bachelor-2/09-functional-programming/listings/infinite.rs*

```
$ rustc --edition 2021 -O -o infinite infinite.rs && ./infinite
[1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
first above a million: Some(1346269)
27 reaches 1 after 111 steps, peaking at 9232
```

***Output 9.5.** Each sequence is computed only as far as asked.*

On real data, a pipeline states the cleaning rules one per line. The weather log of [Chapter 7](https://one-course.com/books/computer-science/4/en/chapter/7-enums-pattern-matching-and-error-handling#ch-b2-rust-enums-and-errors) gives each station’s mean temperature:

```rust
        let (sum, n) = text
            .lines()
            .skip(1)                                              // the header
            .map(|line| line.split(',').collect::<Vec<&str>>())
            .filter(|f| f[1] == station)
            .filter_map(|f| f[2].parse::<f64>().ok())             // empty fields fail to parse
            .filter(|&t| t != -99.0)                              // the stations' error code
            .fold((0.0, 0), |(s, n), t| (s + t, n + 1));
        println!("{station:<10} {n} readings, mean {:.2}", sum / n as f64);
```

***Listing 9.5.** A mean as a [fold](#def-b2-functional-programming-fold) code/bachelor-2/09-functional-programming/listings/pipeline.rs*

```
$ ./pipeline
Hilltop    362 readings, mean 10.63
Riverside  361 readings, mean 12.04
```

***Output 9.6.** The duplicated Riverside line is counted here, unlike in [Chapter 7](https://one-course.com/books/computer-science/4/en/chapter/7-enums-pattern-matching-and-error-handling#ch-b2-rust-enums-and-errors). Some lines are left out.*

The whole pipeline is one loop over the lines, with no vector of all the lines: each line is split, tested, parsed and added before the next is read. (Each line’s fields are still collected into a small vector of their own, which `split` followed by `nth` would avoid.) Rust compiles such chains to the loop one would write by hand.

## 9.3 Immutable data

A functional program does not modify data: an update builds a new value. Done naively, every update copies everything. Done well, the new value shares all the parts it did not change with the old one.

**Definition 9.5 (Persistent data structure, structural sharing, path copying).**

A data structure is *persistent* if an update returns a new version and leaves every old version intact and usable. *Structural sharing* is the use of the same nodes by several versions; *path copying* implements an update of a tree by copying only the nodes on the path from the root to the place of the change, the new nodes pointing to the old, unchanged subtrees.

Sharing needs [shared ownership](https://one-course.com/books/computer-science/4/en/chapter/2-copying-moving-and-smart-pointers#def-b2-cpp-copy-move-shared-ptr): a node with several [owners](https://one-course.com/books/computer-science/4/en/chapter/6-rust-ownership-and-borrowing#def-b2-rust-ownership-ownership) must be freed only when the last one goes. `Rc<T>` (reference counted) does this: `Rc::clone` copies the pointer and increments a count stored next to the value; dropping an `Rc` decrements it, and the value is freed at zero.

```rust
pub enum List {
    Nil,
    Cons(i32, Rc<List>), // Rc: shared ownership, freed when the last owner goes
}
use List::*;

pub fn cons(x: i32, rest: &Rc<List>) -> Rc<List> {
    Rc::new(Cons(x, Rc::clone(rest))) // clones the pointer, not the list: count + 1
}

pub fn to_vec(l: &List) -> Vec<i32> {
    let mut out = Vec::new();
    let mut cur = l;
    while let Cons(x, rest) = cur {
        out.push(*x);
        cur = rest;
    }
    out
}

#[allow(dead_code)]
fn main() {
    let nil = Rc::new(Nil);
    let tail = cons(3, &cons(2, &cons(1, &nil)));          // 3, 2, 1
    let a = cons(10, &tail);                                // 10, 3, 2, 1
    let b = cons(20, &tail);                                // 20, 3, 2, 1
    println!("a = {:?}, b = {:?}", to_vec(&a), to_vec(&b));
    println!("owners of tail: {}", Rc::strong_count(&tail)); // tail itself, a, b
    drop(a);
    println!("after dropping a: {}", Rc::strong_count(&tail));
    println!("tail unchanged: {:?}", to_vec(&tail));
}
```

***Listing 9.6.** Two lists with one tail code/bachelor-2/09-functional-programming/listings/persistent_list.rs*

```
$ rustc --edition 2021 -O -o persistent_list persistent_list.rs && ./persistent_list
a = [10, 3, 2, 1], b = [20, 3, 2, 1]
owners of tail: 3
after dropping a: 2
tail unchanged: [3, 2, 1]
```

***Output 9.7.** The tail is shared, never copied.*

![Two persistent lists sharing a tail. Adding an element at the front costs one node, whatever the length; neither list can change the shared part, since nothing modifies a node once built.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-functional-programming/fig-80e07d9f7efa.svg)

*Two [persistent](#def-b2-functional-programming-persistent) lists sharing a tail. Adding an element at the front costs one node, whatever the length; neither list can change the shared part, since nothing modifies a node once built.*

A search tree is shared the same way. Inserting into a [persistent](#def-b2-functional-programming-persistent) tree rebuilds the path to the new leaf and points everything else at the old version:

```rust
pub fn insert(t: &Tree, k: i32) -> Tree {
    match t {
        None => Some(Rc::new(Node { key: k, left: None, right: None })),
        Some(n) if k < n.key => {
            let left = insert(&n.left, k); // a new left subtree; the right one is shared
            Some(Rc::new(Node { key: n.key, left, right: n.right.clone() }))
        }
        Some(n) if k > n.key => {
            let right = insert(&n.right, k);
            Some(Rc::new(Node { key: n.key, left: n.left.clone(), right }))
        }
        Some(_) => t.clone(), // already there: shared (the path above is still copied)
    }
}
```

***Listing 9.7.** Insertion by [path copying](#def-b2-functional-programming-persistent) code/bachelor-2/09-functional-programming/listings/persistent_bst.rs*

```
$ rustc --edition 2021 -O -o persistent_bst persistent_bst.rs && ./persistent_bst
v1 [65, 98, 133, 189, 251, 320, 412]
v2 [65, 98, 133, 140, 189, 251, 320, 412]
nodes: v1 7, new in v2 4, shared 4
```

***Output 9.8.** Inserting 140: four new nodes, four shared; `v1` still has its seven keys.*

![Path copying, from . v2 owns three copies (189, 65, 133) and the new 140; its dashed pointers lead into v1’s nodes 251 and 98, with all that hangs below them. v1 is untouched.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-functional-programming/fig-8bfb5cdc5a61.svg)

*[Path copying](#def-b2-functional-programming-persistent), from [Output 9.8](#out-b2-functional-programming-pbst). `v2` owns three copies (189, 65, 133) and the new 140; its dashed pointers lead into `v1`’s nodes 251 and 98, with all that hangs below them. `v1` is untouched.*

**Proposition 9.6 (Path copying).**

Inserting a key absent from a [persistent](#def-b2-functional-programming-persistent) search tree, at depth $d$ (the root at depth 0), creates exactly $d + 1$ nodes: copies of the $d$ nodes on the path and the new leaf. Every other node of the old version is shared by the new one.

**Proof.** By induction on $d$. If $d = 0$, the tree is empty and `insert` creates one node. If $d \ge 1$, the root is not the key; `insert` creates one copy of the root and calls itself on one subtree, where the key will be at depth $d - 1$: by induction that call creates $d$ nodes and shares every other node of that subtree. The copy of the root points to the other subtree unchanged (`n.right.clone()` or `n.left.clone()`, a pointer copy). In all, $1 + d$ new nodes, and every old node off the path is reachable from the new root. ∎

## 9.4 Recursion and tail calls

Without loops that update variables, functional programs repeat by recursion. Each pending call costs a stack frame.

**Definition 9.7 (Tail call, tail recursion).**

A call is a *tail call* if it is the last action of the calling function: its result is returned as it is, with nothing left to compute. A function is *tail-recursive* if its recursive calls are tail calls. A compiler that performs *tail-call elimination* turns a tail call into a jump, reusing the frame.

```rust
fn sum_rec(xs: &[u64]) -> u64 {
    match xs {
        [] => 0,
        [first, rest @ ..] => first + sum_rec(rest), // + waits: not a tail call
    }
}

fn main() {
    let xs: Vec<u64> = (1..=1_000_000).collect();
    let small = std::thread::Builder::new().stack_size(1 << 20); // a 1 MiB stack
    let h = small.spawn(move || println!("sum {}", sum_rec(&xs))).unwrap();
    h.join().unwrap();
}
```

***Listing 9.8.** A sum with one frame per element code/bachelor-2/09-functional-programming/listings/deep_recursion.rs*

```
$ rustc --edition 2021 -C opt-level=0 deep_recursion.rs -o deep_recursion
$ sh -c './deep_recursion 2> err.txt; exit $?' 2> /dev/null; echo "exit status $?"
exit status 134
$ grep . err.txt | head -2 | sed 's/ ([0-9]*)//'
thread '<unknown>' has overflowed its stack
fatal runtime error: stack overflow, aborting
$ rustc --edition 2021 -C opt-level=3 deep_recursion.rs -o deep_recursion_o3
$ sh -c './deep_recursion_o3 2> err.txt; exit $?' 2> /dev/null; echo "exit status $?"
exit status 134
```

***Output 9.9.** A million frames do not fit in 1 MiB, with or without optimisation. Status 134 is the abort signal: $128 + 6$.*

`first + sum_rec(rest)` is not a [tail call](#def-b2-functional-programming-tail): the addition waits for the result. Rust does not promise [tail-call elimination](#def-b2-functional-programming-tail) even for real [tail calls](#def-b2-functional-programming-tail); the optimiser may do it, but a program that depends on it is fragile. The remedy is a method.

**Method 9.8 (The accumulator transformation).**

To make a recursion that combines its result with pending work into a loop:

1. add a parameter, the accumulator, that carries the work done so far, and start it at the neutral value of the combination (0 for a sum);
2. in the recursive case, do the pending work on the accumulator *before* the call, so that the call becomes a [tail call](#def-b2-functional-programming-tail) : `sum_acc(rest, acc + first)` ;
3. return the accumulator in the base case;
4. replace the [tail call](#def-b2-functional-programming-tail) by updating the parameters and jumping back to the start: a `loop` or `while` .

The transformation is correct when the combination is associative, since it regroups $x_1 + (x_2 + (\dots))$ as $((0 + x_1) + x_2) + \dots$.

```rust
fn sum_acc(xs: &[u64], acc: u64) -> u64 {
    match xs {
        [] => acc,
        [first, rest @ ..] => sum_acc(rest, acc + first), // a tail call: nothing waits for it
    }
}

fn sum_loop(mut xs: &[u64]) -> u64 {
    let mut acc = 0;
    while let [first, rest @ ..] = xs {
        // the same steps, with the call replaced by a jump
        acc += first;
        xs = rest;
    }
    acc
}
```

***Listing 9.9.** Steps 1–3, then step 4 code/bachelor-2/09-functional-programming/listings/tail_loop.rs*

```
$ rustc --edition 2021 -O -o tail_loop tail_loop.rs && ./tail_loop
500000500000 500500
```

***Output 9.10.** The loop sums the million numbers on the same 1 MiB stack; the accumulator version is run on the first thousand.*

## 9.5 Reasoning by equations

**Definition 9.9 (Pure function, side effect, referential transparency).**

A *side effect* is any effect of a call besides its result: a change to a variable outside it, an input or output, a [panic](https://one-course.com/books/computer-science/4/en/chapter/7-enums-pattern-matching-and-error-handling#def-b2-rust-enums-and-errors-panic). A function is *pure* if its result depends only on its arguments and it has no side effect. An expression is *referentially transparent* if replacing it by its value does not change the program.

**Definition 9.10 (Equational reasoning).**

*Equational reasoning* proves properties of [pure](#def-b2-functional-programming-pure) programs by rewriting: each defining equation of a function may be used, left to right or right to left, as an equality of values, as in algebra.

Write a list as $[\,]$ or $x : xs$, an element in front of a list. The [map operation](#def-b2-functional-programming-fold) and the right [fold](#def-b2-functional-programming-fold) are defined by the equations

$$
\begin{align*}
\mathrm{map}\,f\,[\,] &= [\,], & \mathrm{map}\,f\,(x : xs) &= f\,x : \mathrm{map}\,f\,xs,\\
\mathrm{foldr}\,g\,z\,[\,] &= z, & \mathrm{foldr}\,g\,z\,(x : xs) &= g\,x\,(\mathrm{foldr}\,g\,z\,xs).
\end{align*}
$$

**Theorem 9.11 (Map fusion).**

For all functions $f$, $g$ and every finite list $xs$, $\mathrm{map}\,f\,(\mathrm{map}\,g\,xs) = \mathrm{map}\,(f
\circ g)\,xs$.

**Proof.** By structural induction on $xs$. For $[\,]$: both sides are $[\,]$ by the first equation. For $x : xs$, assuming the claim for $xs$:

$$
\begin{align*}
\mathrm{map}\,f\,(\mathrm{map}\,g\,(x : xs)) &= \mathrm{map}\,f\,(g\,x : \mathrm{map}\,g\,xs)
= f\,(g\,x) : \mathrm{map}\,f\,(\mathrm{map}\,g\,xs)\\
&= (f \circ g)\,x : \mathrm{map}\,(f \circ g)\,xs,
\end{align*}
$$

by the second equation twice and the hypothesis; the right-hand side is $\mathrm{map}\,(f \circ g)\,(x : xs)$. ∎

For Rust this says that `.map(g).map(f)` and `.map(|x| f(g(x)))` give the same elements, provided `f` and `g` are [pure](#def-b2-functional-programming-pure): with [side effects](#def-b2-functional-programming-pure) the order of the effects changes ([Output 9.4](#out-b2-functional-programming-lazy) shows them interleaved). Compilers use such laws to merge passes; programmers use them to restructure code without retesting by hand. The test crate `tests/functional` checks this law, [filter](#def-b2-functional-programming-fold) fusion and the [fold](#def-b2-functional-programming-fold) laws on 500 generated lists.

**Proposition 9.12 (Map and filter are folds).**

For every finite list $xs$, $\mathrm{map}\,f\,xs = \mathrm{foldr}\,(\lambda x\,acc.\ f\,x : acc)\,[\,]\,xs$, and $\mathrm{filter}\,p\,xs = \mathrm{foldr}\,(\lambda x\,acc.\ \text{if } p\,x \text{ then } x : acc \text{ else }
acc)\,[\,]\,xs$.

**Proof.** For the map, by induction on $xs$. For $[\,]$ both sides are $[\,]$. For $x : xs$, the right side is $(\lambda x\,acc.\
f\,x : acc)\,x\,(\mathrm{foldr}\,\dots\,xs) = f\,x : \mathrm{foldr}\,\dots\,xs = f\,x : \mathrm{map}\,f\,xs$ by the hypothesis, which is $\mathrm{map}\,f\,(x : xs)$. For the [filter](#def-b2-functional-programming-fold), with $\mathrm{filter}\,p\,(x : xs) = x :
\mathrm{filter}\,p\,xs$ if $p\,x$ and $\mathrm{filter}\,p\,xs$ otherwise, the same induction with two cases. ∎

**In practice — Iterators in practice.**

Prefer a chain of adaptors to an index loop when each step has a name (`filter`, `map`, `sum`): it cannot read out of bounds, and it is as fast. Keep the [closures](#def-b2-functional-programming-closure) [pure](#def-b2-functional-programming-pure); put [side effects](#def-b2-functional-programming-pure) at the end of the chain, in a `for` loop or a `for_each`. Reach for `Rc` and [persistent](#def-b2-functional-programming-persistent) structures when several versions must live together (undo, snapshots, concurrent readers); for one version updated in place, a plain `Vec` or `HashMap` is simpler and faster.

## 9.6 Exercises

**Exercise 9.1 ★.**

Predict the lines printed, in order, then check in the solution. How many elements of `v` are read?

```rust
    let v = [1, 2, 3, 4];
    let it = v.iter().inspect(|x| println!("a{x}")).map(|x| x * 10);
    let it = it.inspect(|x| println!("b{x}"));
    println!("start");
    let s: i32 = it.filter(|x| x % 20 == 0).take(1).sum();
    println!("sum {s}");
```

***Listing 9.10.** A [lazy](#def-b2-functional-programming-lazy) chain with `inspect` code/bachelor-2/09-functional-programming/listings/exo_lazy_order.rs*

**Solution of Exercise 9.1.**

```
$ rustc --edition 2021 -O -o exo_lazy_order exo_lazy_order.rs && ./exo_lazy_order
start
a1
b10
a2
b20
sum 20
```

***Output 9.12.** The order.*

Nothing runs before `sum`. Then 1 goes through both `inspect`s, becomes 10 and is refused by the [filter](#def-b2-functional-programming-fold); 2 becomes 20, passes, and `take(1)` has its element and stops asking. Two elements of `v` are read, and 3 and 4 never.

**Exercise 9.2 ★.**

The program does not compile. Read the error in the solution, fix it in the signature of `for_each_loan`, and explain why the compiler cannot accept `Fn` here.

```rust
fn for_each_loan(days: &[u32], f: impl Fn(u32)) {
    for &d in days {
        f(d);
    }
}

fn main() {
    let days = [3, 25, 30, 12, 22];
    let mut late = 0;
    for_each_loan(&days, |d| {
        if d > 21 {
            late += 1;
        }
    });
    println!("{late} late");
}
```

***Listing 9.11.** Counting late loans code/bachelor-2/09-functional-programming/listings/exo_fnmut.rs*

**Solution of Exercise 9.2.**

```
error[E0594]: cannot assign to `late`, as it is a captured variable in a `Fn` closure
  --> exo_fnmut.rs:14:13
   |
 3 | fn for_each_loan(days: &[u32], f: impl Fn(u32)) {
   |                                   ------------ change this to accept `FnMut` instead of `Fn`
14 |             late += 1;
   |             ^^^^^^^^^ cannot assign
```

***Output 9.13.** The error, shortened. Some lines are left out.*

The [closure](#def-b2-functional-programming-closure) adds to `late`, so it implements `FnMut` only. The parameter becomes `mut f: impl FnMut(u32)`. `Fn` promises that the [closure](#def-b2-functional-programming-closure) can be called through a shared reference, possibly from several places at once; a [closure](#def-b2-functional-programming-closure) that modifies a captured variable needs exclusive access during each call, which only `FnMut` (called through `&mut`) gives. The program then prints `3 late`.

**Exercise 9.3 ★.**

Write `compose(f, g)`, which returns the [closure](#def-b2-functional-programming-closure) $x \mapsto f(g(x))$, generic over the three types involved. Then write `compose_all`, which composes a vector of boxed functions of one type, the last applied first.

**Solution of Exercise 9.3.**

```rust
pub fn compose<A, B, C>(f: impl Fn(B) -> C, g: impl Fn(A) -> B) -> impl Fn(A) -> C {
    move |x| f(g(x)) // first g, then f: (f o g)(x) = f(g(x))
}

/// The composition of a list of functions of one type, applied from the last to the first.
pub fn compose_all<T>(fs: Vec<Box<dyn Fn(T) -> T>>) -> impl Fn(T) -> T {
    move |x| fs.iter().rev().fold(x, |acc, f| f(acc))
}
```

*Composition code/bachelor-2/09-functional-programming/exercises/compose.rs*

The [closure](#def-b2-functional-programming-closure) returned by `compose` must own `f` and `g`, hence `move`. `compose_all` [folds](#def-b2-functional-programming-fold) over the functions from the last to the first, so `compose_all(vec![f, g, h])(x)` is $f(g(h(x)))$; the test checks $((2 + 1)^2) - 3 = 6$.

**Exercise 9.4 ★.**

Predict the three sizes printed, on a target with 8-byte pointers, from what each [closure](#def-b2-functional-programming-closure) captures and how.

```rust
    let rate: u32 = 10;
    let title = String::from("Seven Comets");
    let pages: [u64; 4] = [65, 133, 412, 98];

    let a = |d: u32| d * 2;                       // captures nothing
    let b = |d: u32| d * rate + title.len() as u32; // captures rate and title by reference
    let c = move |i: usize| pages[i] + rate as u64; // moves pages and rate in
    println!("{} {} {}", size_of_val(&a), size_of_val(&b), size_of_val(&c));
    println!("{} {} {}", a(1), b(1), c(1));
```

***Listing 9.12.** Three [closures](#def-b2-functional-programming-closure) code/bachelor-2/09-functional-programming/listings/exo_sizes.rs*

**Solution of Exercise 9.4.**

```
$ rustc --edition 2021 -O -o exo_sizes exo_sizes.rs && ./exo_sizes
0 16 40
2 22 143
```

***Output 9.14.** Sizes, then values.*

`a` captures nothing: 0 bytes, like a plain function. `b` reads `rate` and `title` and captures them by reference: two pointers, 16 bytes. `c` moves in the array of four `u64` (32 bytes) and the `u32`, 36 bytes, padded to 40 for the alignment of the `u64`s.

**Exercise 9.5 ★★.**

Predict the four values. Which of the four [folds](#def-b2-functional-programming-fold) would give the same result as a right [fold](#def-b2-functional-programming-fold) with the same function, arguments swapped?

```rust
fn main() {
    let xs = [3, 1, 4, 1, 5];
    let a = xs.iter().fold(0, |acc, x| acc * 10 + x);
    let b = xs.iter().rev().fold(0, |acc, x| acc * 10 + x);
    let c = xs.iter().fold(Vec::new(), |mut acc, &x| { acc.insert(0, x); acc });
    let d = xs.iter().fold((i32::MAX, i32::MIN), |(lo, hi), &x| (lo.min(x), hi.max(x)));
    println!("{a} {b} {c:?} {d:?}");
}
```

***Listing 9.13.** Four [folds](#def-b2-functional-programming-fold) code/bachelor-2/09-functional-programming/listings/exo_folds.rs*

**Solution of Exercise 9.5.**

```
$ rustc --edition 2021 -O -o exo_folds exo_folds.rs && ./exo_folds
31415 51413 [5, 1, 4, 1, 3] (1, 5)
```

***Output 9.15.** The four values.*

`a` reads the digits in order, 31415; `b` in reverse, 51413; `c` inserts each element at the front, reversing the list; `d` keeps the minimum and maximum, `(1, 5)`. A left [fold](#def-b2-functional-programming-fold) over the reversed list is a right [fold](#def-b2-functional-programming-fold) with the arguments swapped, so `b` is the right [fold](#def-b2-functional-programming-fold) of `a`’s function. Only `d` gives the same result from either side, because `min` and `max` are associative and commutative; the right [fold](#def-b2-functional-programming-fold) of `c`’s function rebuilds the list in its original order.

**Exercise 9.6 ★★.**

The program means to print the number of long titles, then the titles. Explain the error, and give two fixes: one that builds the filtered iterator twice, one that collects it once.

```rust
fn main() {
    let titles = ["The Silent Code", "Seven Comets", "The Paper Forest", "Harbour Lights"];
    let long = titles.iter().filter(|t| t.len() > 13);
    println!("{} long titles", long.count());
    for t in long {
        println!("{t}");
    }
}
```

***Listing 9.14.** An iterator used twice code/bachelor-2/09-functional-programming/listings/exo_twice.rs*

**Solution of Exercise 9.6.**

```
error[E0382]: use of moved value: `long`
   --> exo_twice.rs:7:14
    |
  5 |     let long = titles.iter().filter(|t| t.len() > 13);
    |         ---- move occurs because `long` has type `Filter<std::slice::Iter<'_, &str>, {closure@exo_twice.rs:5:37: 5:40}>`, which does not implement the `Copy` trait
  6 |     println!("{} long titles", long.count());
    |                                     ------- `long` moved due to this method call
  7 |     for t in long {
```

***Output 9.16.** The error, shortened. Some lines are left out.*

`count` takes the iterator by value and runs it to the end, so `long` no longer exists for the loop; an iterator is a cursor, not a collection. Fix 1: a [closure](#def-b2-functional-programming-closure) that builds it, `let long = || titles.iter().filter(|t| t.len() > 13);`, then `long().count()` and `for t in long()`; the [filter](#def-b2-functional-programming-fold) runs twice. Fix 2: `let long: Vec<_> = ... .collect();`, then `long.len()` and `for t in &long`; the [filter](#def-b2-functional-programming-fold) runs once, at the cost of a vector.

**Exercise 9.7 ★★.**

Write `frequencies(text) -> HashMap<String, u32>` as a single chain ending with a [fold](#def-b2-functional-programming-fold), words split at non-alphanumeric characters and lowercased, and `top(text, k)`, the $k$ most frequent words, ties broken alphabetically.

**Solution of Exercise 9.7.**

```rust
pub fn frequencies(text: &str) -> HashMap<String, u32> {
    text.split(|c: char| !c.is_alphanumeric())
        .filter(|w| !w.is_empty())
        .map(|w| w.to_lowercase())
        .fold(HashMap::new(), |mut m, w| {
            *m.entry(w).or_insert(0) += 1;
            m
        })
}

/// The k most frequent words, ties broken alphabetically.
pub fn top(text: &str, k: usize) -> Vec<(String, u32)> {
    let mut v: Vec<(String, u32)> = frequencies(text).into_iter().collect();
    v.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
    v.into_iter().take(k).collect()
}
```

*Frequencies by one [fold](#def-b2-functional-programming-fold) code/bachelor-2/09-functional-programming/exercises/word_freq.rs*

The [fold](#def-b2-functional-programming-fold)’s accumulator is the map itself, [moved from](https://one-course.com/books/computer-science/4/en/chapter/6-rust-ownership-and-borrowing#def-b2-rust-ownership-move) step to step. `then_with` breaks ties in the count by the word. The test checks a sentence in which *the* appears four times in three spellings.

**Exercise 9.8 ★★.**

Prove by structural induction that $\mathrm{foldr}\,(:)\,[\,]\,xs = xs$ for every finite list: the right [fold](#def-b2-functional-programming-fold) of the list constructor is the identity. What does the left [fold](#def-b2-functional-programming-fold) of $(\lambda acc\,x.\ x : acc)$ from $[\,]$ give?

**Solution of Exercise 9.8.**

For $[\,]$: $\mathrm{foldr}\,(:)\,[\,]\,[\,] = [\,]$. For $x : xs$: $\mathrm{foldr}\,(:)\,[\,]\,(x : xs) = x :
\mathrm{foldr}\,(:)\,[\,]\,xs = x : xs$, by the hypothesis. The left [fold](#def-b2-functional-programming-fold) of $(\lambda acc\,x.\ x : acc)$ from $[\,]$ puts each element in front of the previous ones: it reverses the list (`c` of [Exercise 9.5](#exo-b2-functional-programming-5)). The crate checks the first law on 500 lists.

**Exercise 9.9 ★★.**

Write a [persistent](#def-b2-functional-programming-persistent) queue from two [persistent](#def-b2-functional-programming-persistent) lists: `push` adds to the back list, `pop` takes from the front list, and when the front is empty, reverses the back into the front. Test first-in first-out order and that an old version still holds its elements.

**Solution of Exercise 9.9.**

```rust
    pub fn push(&self, x: T) -> Self {
        let back = Rc::new(List::Cons(x, Rc::clone(&self.back)));
        Queue { front: Rc::clone(&self.front), back }
    }

    /// The first element, the rest of the queue, and the nodes copied by a reversal.
    pub fn pop(&self) -> Option<(T, Self, usize)> {
        let (front, steps) = match self.front.as_ref() {
            List::Nil => reverse(&self.back), // empty front: the back, reversed
            List::Cons(..) => (Rc::clone(&self.front), 0),
        };
        let back = if steps > 0 { Rc::new(List::Nil) } else { Rc::clone(&self.back) };
        match front.as_ref() {
            List::Nil => None,
            List::Cons(x, rest) => {
                Some((x.clone(), Queue { front: Rc::clone(rest), back }, steps))
            }
        }
    }
```

*Push, and pop with a reversal code/bachelor-2/09-functional-programming/exercises/queue.rs*

The back list holds the most recent element first, so the front list is its reversal. `pop` returns, besides the element and the new queue, the number of nodes copied by a reversal, which the tests and [Exercise 9.12](#exo-b2-functional-programming-12) use.

**Exercise 9.10 ★★★.**

Prove the [filter](#def-b2-functional-programming-fold) fusion law, $\mathrm{filter}\,p\,(\mathrm{filter}\,q\,xs) = \mathrm{filter}\,(\lambda x.\ q\,x \wedge
p\,x)\,xs$, by structural induction, then the law $\mathrm{map}\,f\,(\mathrm{filter}\,(p \circ f)\,xs) =
\mathrm{filter}\,p\,(\mathrm{map}\,f\,xs)$. Why do both need $p$, $q$ and $f$ [pure](#def-b2-functional-programming-pure)?

**Solution of Exercise 9.10.**

[Filter](#def-b2-functional-programming-fold) fusion, by induction on $xs$. For $[\,]$ both sides are $[\,]$. For $x : xs$: if $q\,x$ is false, the inner [filter](#def-b2-functional-programming-fold) drops $x$ and the left side is $\mathrm{filter}\,p\,(\mathrm{filter}\,q\,xs)$; the right side drops $x$ too, since $q\,x \wedge p\,x$ is false, and the hypothesis closes the case. If $q\,x$ is true, the left side is $\mathrm{filter}\,p\,(x : \mathrm{filter}\,q\,xs)$, which keeps $x$ exactly when $p\,x$, as the right side does, and the tails agree by the hypothesis. The second law: if $p\,(f\,x)$, the left side is $f\,x : \mathrm{map}\,f\,
(\mathrm{filter}\,(p \circ f)\,xs)$ and the right side $\mathrm{filter}\,p\,(f\,x : \mathrm{map}\,f\,xs) = f\,x :
\mathrm{filter}\,p\,(\mathrm{map}\,f\,xs)$; otherwise both drop the element; the hypothesis gives the tails. With [side effects](#def-b2-functional-programming-pure) the laws fail as programs: the left side of the first calls $p$ only on elements that pass $q$, and the second law calls $f$ once or twice per element depending on the side.

**Exercise 9.11 ★★★.**

Write a [persistent](#def-b2-functional-programming-persistent) map from `u32` keys to values by [path copying](#def-b2-functional-programming-persistent), where inserting an existing key replaces its value in the new version only. Test it by inserting 1000 random pairs, keeping every version, and checking a sample of versions against a `BTreeMap` snapshot taken at the same step.

**Solution of Exercise 9.11.**

```rust
fn insert<V: Clone>(t: &Option<Rc<Node<V>>>, key: u32, value: V) -> Rc<Node<V>> {
    match t {
        None => Rc::new(Node { key, value, left: None, right: None }),
        Some(n) => {
            let (left, right) = (n.left.clone(), n.right.clone());
            let mut copy = Node { key: n.key, value: n.value.clone(), left, right };
            if key < n.key {
                copy.left = Some(insert(&n.left, key, value));
            } else if key > n.key {
                copy.right = Some(insert(&n.right, key, value));
            } else {
                copy.value = value; // the same key: a new value, in the copy only
            }
            Rc::new(copy)
        }
    }
}
```

*Insertion that replaces in the copy code/bachelor-2/09-functional-programming/exercises/pmap.rs*

Each step copies the node it passes through, sharing the untouched child; at the key, the copy takes the new value, and the old node keeps the old one. The test inserts 1000 pairs over 100 keys and compares every 37th version, key by key, with the `BTreeMap` snapshot of the same step.

**Exercise 9.12 ★★★.**

In the queue of [Exercise 9.9](#exo-b2-functional-programming-9), used one version after the other, each element is moved from the back to the front once, so $n$ operations cost $O(n)$ in all: $O(1)$ amortised. Show that this bound fails for [persistent](#def-b2-functional-programming-persistent) use: give a sequence of operations on a queue of $n$ elements, reusing an old version, in which each of $m$ pops costs $n$ steps, so $m$ pops cost $mn$. Which assumption of the amortised argument breaks?

**Solution of Exercise 9.12.**

Push $n$ elements into an empty queue: all are in the back list, the front is empty; call this version $q$. Now pop $q$, keep the element, throw away the new queue, and pop $q$ again, $m$ times: each pop finds the front of $q$ empty and reverses its back list of $n$ nodes, $n$ steps, since $q$ itself never changes. Total $mn$; the test checks two pops of an old version costing 11 each. The amortised argument charges each element’s move to the push that brought it, and assumes that a move, once paid, is never needed again; with persistence the same old version, with its unpaid reversal, can be used any number of times.

## 9.7 Problem: A spreadsheet that never forgets

**Problem 9.1.**

Weekend problem — A spreadsheet that never forgets

A spreadsheet’s undo button needs every earlier state of the sheet. Saving a full copy at each edit costs $n$ cells per edit. This problem builds a sheet whose cells are kept in a [persistent](#def-b2-functional-programming-persistent) balanced search tree, with formulas as [closures](#def-b2-functional-programming-closure) evaluated only when asked, and counts what a thousand versions really cost.

**Part I — Formulas as closures.**

```rust
pub type Formula = Rc<dyn Fn(&Sheet) -> f64>; // reads other cells of the same version

#[derive(Clone)]
pub enum Cell {
    Num(f64),
    Formula(Formula),
}

pub struct Node {
    key: u32,
    cell: Cell,
    left: Link,
    right: Link,
}
type Link = Option<Rc<Node>>;

#[derive(Clone)]
pub struct Sheet {
    root: Link,
    pub evaluations: Rc<Counter<u32>>, // formulas run so far, shared by all versions
}
```

***Listing 9.15.** Cells, nodes and versions code/bachelor-2/09-functional-programming/listings/sheet.rs*

1. What is the type of a formula? Why does it take a `&Sheet` rather than capturing one?
2. Why is a formula an `Rc<dyn Fn>` and not a `Box<dyn Fn>` ? (Look at what `set` does to the cells on its path.)
3. Which [trait](https://one-course.com/books/computer-science/4/en/chapter/8-traits-and-generics#def-b2-rust-traits-and-generics-trait) among `Fn` , `FnMut` and `FnOnce` must a formula implement, and why not the others?
4. In `sheet_demo.rs` , each column total is `move |s| (0..9).map(|r| s.value(10 * r + c)).sum()` . What does it capture, and why must it be `move` ?
5. Is a formula a [pure function](#def-b2-functional-programming-pure) of the sheet? What would break if it modified a captured variable?
6. What does a formula that reads its own cell do when evaluated?

**Part II — Cells evaluated lazily.**

```rust
impl Sheet {
    pub fn new(cells: &[(u32, Cell)]) -> Sheet {
        Sheet { root: build(cells), evaluations: Rc::new(Counter::new(0)) }
    }

    pub fn set(&self, key: u32, cell: Cell) -> Sheet {
        Sheet { root: set(&self.root, key, cell), evaluations: Rc::clone(&self.evaluations) }
    }
    /// The value of a cell; a formula runs only now, when its value is asked for.
    pub fn value(&self, key: u32) -> f64 {
        match self.get(key) {
            Cell::Num(x) => *x,
            Cell::Formula(f) => {
                self.evaluations.set(self.evaluations.get() + 1);
                f(self)
            }
        }
    }
}
```

***Listing 9.16.** Making a version, and reading a value code/bachelor-2/09-functional-programming/listings/sheet.rs*

7. How many formulas run when the sheet is built? Check against the output.
8. Reading the total of column 5 runs how many formulas? How many cells are read?
9. The counter `evaluations` is a `Cell<u32>` behind an `Rc` . Why not a plain `u32` ?
10. After the edits, `value(95)` is asked of version 0 and of version 1000. Explain the two answers.
11. A formula’s value is recomputed at each request. Describe a cache, and the condition on versions under which a cached value stays valid.
12. Why is laziness useful when most of a thousand versions are never displayed?

**Part III — Every version kept.**

```rust
fn set(t: &Link, key: u32, cell: Cell) -> Link {
    let n = t.as_ref().expect("only existing cells are set");
    let (left, right, cell) = if key < n.key {
        (set(&n.left, key, cell), n.right.clone(), n.cell.clone())
    } else if key > n.key {
        (n.left.clone(), set(&n.right, key, cell), n.cell.clone())
    } else {
        (n.left.clone(), n.right.clone(), cell)
    };
    Some(Rc::new(Node { key: n.key, cell, left, right })) // one new node per level of the path
}
```

***Listing 9.17.** Setting a cell by [path copying](#def-b2-functional-programming-persistent) code/bachelor-2/09-functional-programming/listings/sheet.rs*

13. `set` differs from `insert` of [Listing 9.7](#lst-b2-functional-programming-pbst) : the key always exists. How many nodes does setting a cell at depth $d$ create, by [Proposition 9.6](#prop-b2-functional-programming-path-copy) ?
14. `build` puts the middle key at the root. Prove that a tree built this way from $n$ keys has at most $\lfloor \log_2 n \rfloor + 1$ levels.
15. What does `cell.clone()` cost for a `Num` , and for a `Formula` ?
16. `distinct_nodes` walks every version but stops at nodes already seen. Why is its cost proportional to the number of distinct nodes, plus the number of versions?
17. Which nodes do version 0 and version 1000 share? (Think of the cells never edited, and of their ancestors.)
18. The edits go to cells $37i \bmod 90$ . Why are all 90 number cells edited, and how often each?

**Part IV — Memory, proved and measured.**

```
$ ./sheet_demo
100 cells, formulas run: 0
total of column 5 in version 0: 27
after 1000 edits: version 0 says 27, version 1000 8595
formulas run: 3
distinct nodes 5891, bound n + k(ceil(log2 n) + 1) = 8100
40 bytes per node; full copies would hold 100100 nodes
```

***Output 9.11.** 100 cells, 1000 edits, all versions kept. Some lines are left out.*

19. Prove that $k$ edits of an $n$ -cell sheet built by `build` create at most $k(\lfloor \log_2 n \rfloor + 1)$ nodes, so that all versions hold at most $n + k(\lfloor \log_2 n \rfloor + 1)$ nodes, and so at most the looser $n + k(\lceil \log_2 n \rceil + 1)$ that the program prints.
20. Compare with the count printed. Why is the count below the bound?
21. Full copies would hold $(k + 1)n$ nodes. What is the ratio here, and how does it grow with $n$ ?
22. At 40 bytes per node, how much memory do the thousand versions take? Is the `Rc` count included in the 40?
23. Old versions that nobody holds are freed. Which line of `sheet_demo.rs` keeps them all alive?
24. State the result of the problem.

**Solution of Problem 9.1.**

**1.** `Rc<dyn Fn(&Sheet) -> f64>`. The sheet is a parameter so that the formula reads the version it is evaluated in: a captured sheet would be one fixed version, and the sheet would contain a formula owning the sheet, a cycle of `Rc` that is never freed.

**2.** `set` clones the cell of every node it copies (`n.cell.clone()`). A `Box<dyn Fn>` cannot be cloned; an `Rc` clones by incrementing a count, sharing the [closure](#def-b2-functional-programming-closure).

**3.** `Fn`: a formula is called any number of times, through shared references, from any version. `FnMut` would need exclusive access to the formula; `FnOnce` allows a single call.

**4.** The column number `c`, by value. `c` is the loop variable and dies at the end of each turn of the loop; the [closure](#def-b2-functional-programming-closure) lives in the sheet, so it must own its copy.

**5.** Yes: its result depends only on the cells of the sheet it is given. A formula that modified a captured variable would give results that depend on how often and in which order cells were evaluated, which laziness makes unpredictable; `Fn` forbids it anyway.

**6.** It calls `value` on its own cell, which calls the formula again: an infinite recursion, ended by a stack overflow. A real sheet detects cycles before evaluating.

**7.** None: *formulas run: 0*.

**8.** One formula; it reads nine cells, `5, 15, ..., 85`.

**9.** `value` takes `&self`, a shared reference, yet must change the counter; `Cell` allows a change through a shared reference (for a `Copy` value, by `get` and `set`). The `Rc` shares one counter among all versions.

**10.** Version 0 still holds its original cells, whose column total is 27. Version 1000 holds the values written by the edits; the formula, the same [closure](#def-b2-functional-programming-closure), reads those.

**11.** Store, with each formula node, the value computed for a given version. Since a version never changes, a value cached for a version stays valid forever for it; it is valid in a later version too if every cell the formula reads is the same node in both (a pointer comparison), which [path copying](#def-b2-functional-programming-persistent) makes cheap to check.

**12.** Building a version costs $O(\log n)$ whatever its formulas; a version that is never displayed never runs them.

**13.** The key exists at depth $d$, so the path from the root to it has $d + 1$ nodes, and each is copied once; the node of the cell is replaced by a copy holding the new cell. $d + 1$ new nodes, as in [Proposition 9.6](#prop-b2-functional-programming-path-copy), and nothing is added to the tree.

**14.** Let $L(n)$ be the number of levels for $n$ keys. $L(1) = 1$, and for $n \ge 2$ the larger part has $\lfloor n/2 \rfloor$ keys, so $L(n) = 1 + L(\lfloor n/2 \rfloor)$. By induction, $L(n) \le 1 + \lfloor \log_2 \lfloor
n/2 \rfloor \rfloor + 1 = \lfloor \log_2 n \rfloor + 1$, since $\lfloor \log_2 \lfloor n/2 \rfloor \rfloor =
\lfloor \log_2 n \rfloor - 1$ for $n \ge 2$.

**15.** A `Num` copies 16 bytes (the cell); a `Formula` copies a [fat pointer](https://one-course.com/books/computer-science/4/en/chapter/8-traits-and-generics#def-b2-rust-traits-and-generics-trait-object) and increments the `Rc` count: no [closure](#def-b2-functional-programming-closure) is copied.

**16.** `seen.insert` returns `false` for a node already counted, and the walk stops there, so each distinct node is entered once and each version costs one more step for its root.

**17.** Exactly the nodes none of whose descendants is an edited cell: every number cell is edited (question 18), so a node is shared only if its whole subtree holds formula cells, keys 90 to 99. For this tree there are 7 such nodes; all others were copied at least once between the two versions.

**18.** 37 and 90 have no common divisor, so $i \mapsto 37i \bmod 90$ runs through all 90 residues every 90 edits. $1000 = 11 \cdot 90 + 10$: 10 cells are edited 12 times, the other 80 cells 11 times.

**19.** The initial tree has $n$ nodes. By question 13, an edit at depth $d$ creates $d + 1$ nodes, and by question 14, $d + 1 \le \lfloor \log_2 n \rfloor + 1$ (edits never change the shape). So $k$ edits create at most $k(\lfloor \log_2 n \rfloor + 1)$ nodes, and all versions together hold at most $n + k(\lfloor \log_2 n \rfloor + 1)$ distinct nodes, which is at most $n + k(\lceil \log_2 n \rceil + 1)$ since the floor never exceeds the ceiling.

**20.** 5891 against the 8100 printed, and against 7100 for the floor bound. The program’s ceiling formula charges every edit for 8 levels, while the tree has 7; even the floor bound charges every edit for the deepest path, and only 37 of its 100 nodes are on the last level; the average edit creates about 5.8 nodes.

**21.** $100100 / 5891 \approx 17$. Full copies grow as $kn$, the [persistent](#def-b2-functional-programming-persistent) versions as $k \log_2 n$: the ratio grows like $n / \log_2 n$.

**22.** $5891 \times 40 = 235{,}640$ bytes, about 230 KiB. The 40 bytes are the `Node`; each `Rc` allocation also holds a strong and a weak count, 16 more bytes, so about 330 KB in all, against about 5.6 MB for full copies of the nodes at the same size.

**23.** `versions.push(edited)`: the vector owns every version, so no root’s count reaches zero.

**24.** $k$ versions of an $n$-cell sheet in at most $n + k(\lceil \log_2 n \rceil + 1)$ nodes: for 100 cells and 1000 edits, 5891 distinct nodes, under the bound of 8100, against 100100 for full copies.
