University Computer Science — Year 2 · Bachelor Year 2
9Functional 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.
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}");
}
$ rustc --edition 2021 -O -o odd_squares odd_squares.rs && ./odd_squares
364 364
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, 7 and 8: ownership and borrowing, recursive enums with Box, traits and trait objects.
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), or only FnOnce (it gives a captured value away: callable once).
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<_>>());
}
$ rustc --edition 2021 -O -o closures closures.rs && ./closures
40 300
calls 2
Seven Comets
[90, 400]
make_fine returns a closure: its parameters die with the call, so the closure must own copies, hence move. Each closure has its own anonymous type, which is why make_fine declares its result as impl Fn(u32) -> u32, and why closures of different bodies can share a vector only as Box<dyn Fn>, trait objects (Chapter 8). A 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;
fn_once_error.rs calls give twice. Some lines are left out.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 , the map operation with a function gives ; the filter with a predicate keeps the with true, in order; the fold from with a two-argument function gives (a left fold; the right fold is ). 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.
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:?}");
$ 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]
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:
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());
$ 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
On real data, a pipeline states the cleaning rules one per line. The weather log of Chapter 7 gives each station’s mean temperature:
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);
$ ./pipeline
Hilltop 362 readings, mean 10.63
Riverside 361 readings, mean 12.04
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: a node with several owners 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.
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));
}
$ 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]
A search tree is shared the same way. Inserting into a persistent tree rebuilds the path to the new leaf and points everything else at the old version:
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)
}
}
$ 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
v1 still has its seven keys.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 search tree, at depth (the root at depth 0), creates exactly nodes: copies of the 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 . If , the tree is empty and insert creates one node. If , 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 : by induction that call creates 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, 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.
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();
}
$ 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
first + sum_rec(rest) is not a tail call: the addition waits for the result. Rust does not promise tail-call elimination even for real tail calls; 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:
- 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);
- in the recursive case, do the pending work on the accumulator before the call, so that the call becomes a tail call:
sum_acc(rest, acc + first); - return the accumulator in the base case;
- replace the tail call by updating the parameters and jumping back to the start: a
looporwhile.
The transformation is correct when the combination is associative, since it regroups as .
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
}
$ rustc --edition 2021 -O -o tail_loop tail_loop.rs && ./tail_loop
500000500000 500500
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. 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 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 , an element in front of a list. The map operation and the right fold are defined by the equations
Theorem 9.11 (Map fusion)
For all functions , and every finite list , .
Proof. By structural induction on . For : both sides are by the first equation. For , assuming the claim for :
by the second equation twice and the hypothesis; the right-hand side is . ∎
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: with side effects the order of the effects changes (Output 9.4 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 fusion and the fold laws on 500 generated lists.
Proposition 9.12 (Map and filter are folds)
For every finite list , , and .
Proof. For the map, by induction on . For both sides are . For , the right side is by the hypothesis, which is . For the filter, with if and 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 pure; put side effects at the end of the chain, in a for loop or a for_each. Reach for Rc and 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?
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}");
inspect code/bachelor-2/09-functional-programming/listings/exo_lazy_order.rsSolution
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
Nothing runs before sum. Then 1 goes through both inspects, becomes 10 and is refused by the filter; 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.
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");
}
Solution
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
The closure adds to late, so it implements FnMut only. The parameter becomes mut f: impl FnMut(u32). Fn promises that the closure can be called through a shared reference, possibly from several places at once; a 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 , 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
Solution of Exercise 9.3.
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))
}
The closure returned by compose must own f and g, hence move. compose_all folds over the functions from the last to the first, so compose_all(vec![f, g, h])(x) is ; the test checks .
Exercise 9.4 ★
Predict the three sizes printed, on a target with 8-byte pointers, from what each closure captures and how.
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));
Solution
Solution of Exercise 9.4.
$ rustc --edition 2021 -O -o exo_sizes exo_sizes.rs && ./exo_sizes
0 16 40
2 22 143
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 u64s.
Exercise 9.5 ★★
Predict the four values. Which of the four folds would give the same result as a right fold with the same function, arguments swapped?
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:?}");
}
Solution
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)
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 over the reversed list is a right fold with the arguments swapped, so b is the right 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 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.
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}");
}
}
Solution
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 {
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 that builds it, let long = || titles.iter().filter(|t| t.len() > 13);, then long().count() and for t in long(); the filter runs twice. Fix 2: let long: Vec<_> = ... .collect();, then long.len() and for t in &long; the filter 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, words split at non-alphanumeric characters and lowercased, and top(text, k), the most frequent words, ties broken alphabetically.
Solution
Solution of Exercise 9.7.
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()
}
The fold’s accumulator is the map itself, moved from 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 for every finite list: the right fold of the list constructor is the identity. What does the left fold of from give?
Solution
Solution of Exercise 9.8.
For : . For : , by the hypothesis. The left fold of from puts each element in front of the previous ones: it reverses the list (c of Exercise 9.5). The crate checks the first law on 500 lists.
Exercise 9.9 ★★
Write a persistent queue from two 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
Solution of Exercise 9.9.
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))
}
}
}
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 use.
Exercise 9.10 ★★★
Prove the filter fusion law, , by structural induction, then the law . Why do both need , and pure?
Solution
Solution of Exercise 9.10.
Filter fusion, by induction on . For both sides are . For : if is false, the inner filter drops and the left side is ; the right side drops too, since is false, and the hypothesis closes the case. If is true, the left side is , which keeps exactly when , as the right side does, and the tails agree by the hypothesis. The second law: if , the left side is and the right side ; otherwise both drop the element; the hypothesis gives the tails. With side effects the laws fail as programs: the left side of the first calls only on elements that pass , and the second law calls once or twice per element depending on the side.
Exercise 9.11 ★★★
Write a persistent map from u32 keys to values by path copying, 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
Solution of Exercise 9.11.
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)
}
}
}
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, used one version after the other, each element is moved from the back to the front once, so operations cost in all: amortised. Show that this bound fails for persistent use: give a sequence of operations on a queue of elements, reusing an old version, in which each of pops costs steps, so pops cost . Which assumption of the amortised argument breaks?
Solution
Solution of Exercise 9.12.
Push elements into an empty queue: all are in the back list, the front is empty; call this version . Now pop , keep the element, throw away the new queue, and pop again, times: each pop finds the front of empty and reverses its back list of nodes, steps, since itself never changes. Total ; 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 cells per edit. This problem builds a sheet whose cells are kept in a persistent balanced search tree, with formulas as closures evaluated only when asked, and counts what a thousand versions really cost.
Part I — Formulas as closures.
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
}
- What is the type of a formula? Why does it take a
&Sheetrather than capturing one? - Why is a formula an
Rc<dyn Fn>and not aBox<dyn Fn>? (Look at whatsetdoes to the cells on its path.) - Which trait among
Fn,FnMutandFnOncemust a formula implement, and why not the others? - In
sheet_demo.rs, each column total ismove |s| (0..9).map(|r| s.value(10 * r + c)).sum(). What does it capture, and why must it bemove? - Is a formula a pure function of the sheet? What would break if it modified a captured variable?
- What does a formula that reads its own cell do when evaluated?
Part II — Cells evaluated lazily.
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)
}
}
}
}
- How many formulas run when the sheet is built? Check against the output.
- Reading the total of column 5 runs how many formulas? How many cells are read?
- The counter
evaluationsis aCell<u32>behind anRc. Why not a plainu32? - After the edits,
value(95)is asked of version 0 and of version 1000. Explain the two answers. - A formula’s value is recomputed at each request. Describe a cache, and the condition on versions under which a cached value stays valid.
- Why is laziness useful when most of a thousand versions are never displayed?
Part III — Every version kept.
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
}
setdiffers frominsertof Listing 9.7: the key always exists. How many nodes does setting a cell at depth create, by Proposition 9.6?buildputs the middle key at the root. Prove that a tree built this way from keys has at most levels.- What does
cell.clone()cost for aNum, and for aFormula? distinct_nodeswalks every version but stops at nodes already seen. Why is its cost proportional to the number of distinct nodes, plus the number of versions?- Which nodes do version 0 and version 1000 share? (Think of the cells never edited, and of their ancestors.)
- The edits go to cells . 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
- Prove that edits of an -cell sheet built by
buildcreate at most nodes, so that all versions hold at most nodes, and so at most the looser that the program prints. - Compare with the count printed. Why is the count below the bound?
- Full copies would hold nodes. What is the ratio here, and how does it grow with ?
- At 40 bytes per node, how much memory do the thousand versions take? Is the
Rccount included in the 40? - Old versions that nobody holds are freed. Which line of
sheet_demo.rskeeps them all alive? - State the result of the problem.
Solution
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.
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 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, 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 makes cheap to check.
12. Building a version costs whatever its formulas; a version that is never displayed never runs them.
13. The key exists at depth , so the path from the root to it has nodes, and each is copied once; the node of the cell is replaced by a copy holding the new cell. new nodes, as in Proposition 9.6, and nothing is added to the tree.
14. Let be the number of levels for keys. , and for the larger part has keys, so . By induction, , since for .
15. A Num copies 16 bytes (the cell); a Formula copies a fat pointer and increments the Rc count: no 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 runs through all 90 residues every 90 edits. : 10 cells are edited 12 times, the other 80 cells 11 times.
19. The initial tree has nodes. By question 13, an edit at depth creates nodes, and by question 14, (edits never change the shape). So edits create at most nodes, and all versions together hold at most distinct nodes, which is at most 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. . Full copies grow as , the persistent versions as : the ratio grows like .
22. 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. versions of an -cell sheet in at most nodes: for 100 cells and 1000 edits, 5891 distinct nodes, under the bound of 8100, against 100100 for full copies.