এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।
University Computer Science — Year 2 · স্নাতক দ্বিতীয় বর্ষ
7Enums, Pattern Matching and Error Handling
The weather stations write their temperatures with one decimal. A C function reads a field into tenths of a degree, and returns when the field is not a number, the usual C convention.
int temp_tenths(const char *field)
{
char *end;
double t = strtod(field, &end);
if (end == field || *end != '\0')
return -1; /* no number, or garbage after it */
return (int)(t * 10 + (t < 0 ? -0.5 : 0.5));
}
$ gcc -std=c17 -O2 -Wall -Wextra -o temp_code temp_code.c -lm && ./temp_code
4.3 -> 43
-> -1 unreadable?
-0.1 -> -1 unreadable?
n/a -> -1 unreadable?
-12.5 -> -125
A temperature of °C is indistinguishable from a missing one. The function has two kinds of answers, a temperature or a failure, and its return type, int, has room for only one kind: the failure borrowed a value from the temperatures. This chapter gives each kind of answer its own place in the type, and makes the compiler check that every caller looks at both.
You already know
Book 3: a C union stores one of several types in the same bytes, and nothing records which; a C enum names integer constants. An inductive set is defined by base elements and constructors, and a property of all its elements is proved by structural induction: for the base elements, then for each constructor assuming it for the parts. Chapter 6: ownership, Box, and the panic that stops a program on a bug.
7.1 Product and sum types
Definition 7.1 (Product type, sum type, algebraic data type)
A product type holds one value of each of its component types at once: a tuple (A, B) or a struct. A sum type holds one value of exactly one of its component types, together with which one: a Rust enum. The types built from basic types by products and sums, possibly recursively, are the algebraic data types.
Definition 7.2 (Enumeration, enum variant)
A Rust enumeration enum E { V1(...), V2 { ... }, V3 } lists its enum variants, each a name with its own fields, unnamed, named or none. A value of type E is built by one variant, E::V1(...), and records which.
#[derive(Debug)]
enum Shape {
Circle { r: f64 }, // a variant with named fields
Rect { w: f64, h: f64 },
Triangle(f64, f64, f64), // a variant with unnamed fields: the three sides
}
fn area(s: &Shape) -> f64 {
match s {
Shape::Circle { r } => PI * r * r,
Shape::Rect { w, h } => w * h,
Shape::Triangle(a, b, c) => {
let p = (a + b + c) / 2.0; // Heron's formula
(p * (p - a) * (p - b) * (p - c)).sqrt()
}
}
}
fn main() {
let plots = [
Shape::Rect { w: 4.0, h: 5.0 },
Shape::Circle { r: 1.5 },
Shape::Triangle(3.0, 4.0, 5.0),
];
for s in &plots {
println!("{s:?}: area {:.2}", area(s));
}
}
$ rustc --edition 2021 -O -o shapes_enum shapes_enum.rs && ./shapes_enum
Rect { w: 4.0, h: 5.0 }: area 20.00
Circle { r: 1.5 }: area 7.07
Triangle(3.0, 4.0, 5.0): area 6.00
Debug prints each variant with its fields.The names product and sum come from counting.
Proposition 7.3 (Counting the values of algebraic types)
Write for the number of values of a finite type . Then , and for an enum whose variants carry the types (a variant with no field carrying the unit type (), with one value), . In particular and .
Proof. A pair is determined by its first component, choices, and independently its second, choices: pairs. A value of the enum is a variant and a value of ; two values with different variants differ, so the sets of values of the variants are disjoint, and their sizes add. Option<A> has the variants Some(A) and None, carrying (): . Result<A, B> has Ok(A) and Err(B). ∎
A C struct of a bool and a union of an int and a double can be in states, a value of the flag times a member stored, of which the program means only ; the other half are the cases where the flag and the stored member disagree, which nothing prevents. A Rust enum has exactly the values meant.
7.2 Pattern matching
Definition 7.4 (Pattern, pattern matching)
A pattern describes a shape of value: a literal (0), a range (1..=9), a variable that binds whatever it matches (x), the wildcard _, a variant with patterns for its fields (Shape::Rect { w, h }), a tuple of patterns, or alternatives p | q. Pattern matching, match v { p1 => e1, p2 if c => e2, ... }, tries the patterns in order and evaluates the expression of the first one that matches, with its variables bound; an arm may add a guard, if c, a condition on the bound variables.
Definition 7.5 (Exhaustive match)
A match is exhaustive if every value of the matched type matches at least one of its patterns, guards not counted. Rust accepts only exhaustive matches.
fn corners(s: &Shape) -> u32 {
match s {
Shape::Rect { .. } => 4,
Shape::Triangle(..) => 3,
}
}
error[E0004]: non-exhaustive patterns: `&Shape::Circle { .. }` not covered
--> nonexhaustive.rs:10:11
|
10 | match s {
| ^ pattern `&Shape::Circle { .. }` not covered
4 | Circle { r: f64 },
| ------ not covered
Exhaustiveness is what makes a sum type safe to extend: add a variant, and the compiler lists every match that must now handle it, unless the match ends with a wildcard _, which silently takes the new variant too (Exercise 7.2). Write wildcards only where a default is right for every future variant.
7.3 Options and results
Definition 7.6 (Option type)
The option type Option<T> of the standard library is the enum with the variants Some(T) and None. It is the type of a value that may be absent, and replaces the null pointer and the reserved no value code.
fn find<'a>(books: &'a [Book], title: &str) -> Option<&'a Book> {
books.iter().find(|b| b.title == title) // Some(&book) or None: never a null pointer
}
fn pages_of_both(books: &[Book], a: &str, b: &str) -> Option<u32> {
let x = find(books, a)?; // ? : if None, return None from pages_of_both now
let y = find(books, b)?;
Some(x.pages + y.pages)
}
fn main() {
let books = [
Book { title: "The Silent Code", pages: 65 },
Book { title: "The Paper Forest", pages: 133 },
];
match find(&books, "The Paper Forest") {
Some(b) => println!("found, {} pages", b.pages),
None => println!("not found"),
}
if let Some(b) = find(&books, "Seven Comets") {
println!("{} pages", b.pages); // not run: the pattern does not match None
}
let n = find(&books, "Seven Comets").map(|b| b.pages).unwrap_or(0);
println!("{n} {:?} {:?}", pages_of_both(&books, "The Silent Code", "The Paper Forest"),
pages_of_both(&books, "The Silent Code", "Seven Comets"));
}
$ rustc --edition 2021 -O -o option_demo option_demo.rs && ./option_demo
found, 133 pages
0 Some(198) None
match, if let, unwrap_or and ?.The C version returns NULL for not found, and nothing obliges the caller to test it. The first lookup succeeds; the second dereferences NULL.
$ ./null_crash
133 pages
AddressSanitizer:DEADLYSIGNAL
=================================================================
==1000==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000008 (pc 0x5555555555b0 bp 0x7fffffffeca0 sp 0x7fffffffec00 T0)
==1000==The signal is caused by a READ memory access.
==1000==Hint: address points to the zero page.
#0 0x5555555555b0 in main ~/session/null_crash.c:20
SUMMARY: AddressSanitizer: SEGV ~/session/null_crash.c:20 in main
null_crash.c): NULL->pages reads address 8. Some lines are left out.In Rust the book cannot be used before the Option is opened: find(...).pages does not compile, since an Option<&Book> has no field pages. Failures that come with a reason use the second enum.
Definition 7.7 (Result type, error propagation)
The result type Result<T, E> is the enum with the variants Ok(T), a success carrying its value, and Err(E), a failure carrying an error of type E. Error propagation is the return of a failure to the caller: the operator ? applied to a Result gives the value inside Ok, or returns Err(e) from the enclosing function at once, converting e with From::from into that function’s error type.
The stations’ log, data/town/weather.csv, has a line per day and station. Each line is parsed into a Reading or an error that says what is wrong.
pub enum LineError {
FieldCount(usize),
UnknownStation(String),
Missing(&'static str), // an empty field
BadNumber { field: &'static str, text: String }, // not a number
ErrorCode { field: &'static str }, // -99.0, the code for "no measurement"
}
fn number(field: &'static str, text: &str) -> Result<f64, LineError> {
if text.is_empty() {
return Err(LineError::Missing(field));
}
let v: f64 = text.parse()
.map_err(|_| LineError::BadNumber { field, text: text.to_string() })?;
if v == -99.0 {
return Err(LineError::ErrorCode { field });
}
Ok(v)
}
pub fn parse_line(line: &str) -> Result<Reading, LineError> {
let f: Vec<&str> = line.split(',').collect();
if f.len() != 5 {
return Err(LineError::FieldCount(f.len()));
}
let station = match f[1] {
"Hilltop" => Station::Hilltop,
"Riverside" => Station::Riverside,
other => return Err(LineError::UnknownStation(other.to_string())),
};
Ok(Reading {
date: f[0].to_string(),
station,
temp_c: number("temp_c", f[2])?, // ? : on the first bad field, return its error
rain_mm: number("rain_mm", f[3])?,
wind_kmh: number("wind_kmh", f[4])?,
})
}
Result code/bachelor-2/07-rust-enums-and-errors/listings/weather.rsread_log applies parse_line to every line, keeps the readings, records each rejected line with its number and error, and sets aside a second reading for the same day and station. Its own errors, a file that cannot be read or has no header, form a third enum, LogError, and From<std::io::Error> for LogError lets ? convert the error of read_to_string (both are shown in the weekend problem). Run on the log, and on a misspelt file name:
$ rustc --edition 2021 -O weather_parse.rs -o weather_parse
$ ./weather_parse weather.csv
722 readings kept
line 59: rejected, ErrorCode { field: "temp_c" }
line 60: rejected, Missing("temp_c")
line 213: rejected, Missing("temp_c")
line 457: rejected, Missing("temp_c")
line 616: rejected, Missing("temp_c")
line 648: rejected, Missing("temp_c")
line 706: rejected, ErrorCode { field: "temp_c" }
line 717: rejected, Missing("temp_c")
line 332: duplicate of an earlier reading
$ ./weather_parse wether.csv
cannot read wether.csv: No such file or directory (os error 2)
[exit status 1]
? converts the io::Error and returns it from read_log, and main reports it. Below, a missing temperature: ? in parse_line skips the remaining fields, and read_log, which matches instead of using ?, records the error and reads the next line.Definition 7.8 (Panic)
A panic stops the current thread on a condition the program declares impossible: an index out of bounds, an unwrap of None or of Err, an explicit panic!. The values of the thread are dropped, a message gives the place and the cause, and if the thread is the main one the process exits with status 101.
The division of labour is the point. A Result is for failures that the program expects and handles: a bad line in a file, a missing file, a server that does not answer. A panic is for bugs: a state the code was written to make impossible. unwrap says this cannot fail; on input data, it is usually wrong (Exercise 7.6). C++ exceptions (Chapter 1) travel up invisibly through any call; a Result is part of the signature, and each ? marks a place where the function may return.
7.4 Recursive types
Definition 7.9 (Recursive type, box)
A recursive type has a variant or a field whose type contains the type itself. Its values must be finite, and its size must be known: the recursive field is therefore a box, Box<T>, a pointer to a value of type T on the heap that owns it and frees it when dropped.
Without the box, an Expr containing two Exprs would be larger than itself. With it, an Add holds two pointers. An arithmetic expression in one variable is a tree:
pub enum Expr {
Num(i64),
X,
Add(Box<Expr>, Box<Expr>), // a Box: the sub-expression lives on the heap
Mul(Box<Expr>, Box<Expr>),
}
pub fn eval(&self, x: i64) -> i64 {
match self {
Num(n) => *n,
X => x,
Add(a, b) => a.eval(x).wrapping_add(b.eval(x)),
Mul(a, b) => a.eval(x).wrapping_mul(b.eval(x)),
}
}
pub fn simplify(self) -> Expr {
match self {
Add(a, b) => match (a.simplify(), b.simplify()) {
(Num(m), Num(n)) => Num(m.wrapping_add(n)), // fold constants
(Num(0), e) | (e, Num(0)) => e, // 0 + e = e
(a, b) => Add(Box::new(a), Box::new(b)),
},
Mul(a, b) => match (a.simplify(), b.simplify()) {
(Num(m), Num(n)) => Num(m.wrapping_mul(n)),
(Num(0), _) | (_, Num(0)) => Num(0), // 0 * e = 0
(Num(1), e) | (e, Num(1)) => e, // 1 * e = e
(a, b) => Mul(Box::new(a), Box::new(b)),
},
leaf => leaf, // Num and X are already simple
}
}
$ rustc --edition 2021 -O -o expr expr.rs && ./expr
(x * (2 + -1) + 0) * (3 * x + 4 * 0) at x = 5: 75
x * 3 * x at x = 5: 75
The values are integers modulo (wrapping_add, wrapping_mul), a ring in which the rules , and hold exactly; with f64 the second would fail when is infinite.
Proposition 7.10 (Structural recursion terminates)
A function on the values of a recursive type, defined by a match on the variants in which every recursive call is made on a field of the matched value, and whose other operations terminate, terminates on every value.
Proof. By structural induction on the value. On a variant with no recursive field there is no recursive call, and the other operations terminate. On a variant with recursive fields , assume the function terminates on each (the induction hypothesis, legitimate since each is a strictly smaller part of a finite value); the body makes finitely many calls on them, each terminating, plus terminating operations. Every value of a recursive type is finite, being built by finitely many constructions, so the induction covers every value. ∎
eval and simplify recurse only on a and b, the fields of the matched Add or Mul: they terminate. The simplifier is useful only if it is right.
Theorem 7.11 (The simplifier preserves the value)
For every expression e and every x, e.clone().simplify().eval(x) == e.eval(x).
Proof. By structural induction on e. Write for e.eval(x) and for the simplified expression. For Num and X, . For Add(a, b), the induction hypothesis gives and , and . The first arm returns Num(m + n) when and , whose value is . The second returns when , of value , or symmetrically. The third returns Add(S(a), S(b)), of value . In every arm the value is . The Mul case is the same with the rules and of the ring (Exercise 7.11). ∎
The test crate tests/enums checks the theorem on 3000 random expressions, and checks that simplifying twice changes nothing. A binary search tree is the same kind of type; bst.rs inserts the page counts of seven books.
#[derive(Debug, Default, Clone, PartialEq)]
pub enum Tree {
#[default]
Leaf,
Node(Box<Tree>, i32, Box<Tree>), // left subtree, key, right subtree
}
use std::cmp::Ordering;
use Tree::*;
impl Tree {
pub fn insert(&mut self, k: i32) {
match self {
Leaf => *self = Node(Box::new(Leaf), k, Box::new(Leaf)),
Node(left, key, right) => match k.cmp(key) {
Ordering::Less => left.insert(k),
Ordering::Greater => right.insert(k),
Ordering::Equal => {} // already there
},
}
}
$ rustc --edition 2021 -O -o bst bst.rs && ./bst
[65, 98, 133, 189, 251, 320, 412], height 4, contains 98: true, contains 99: false
Box: the node owns its children, and dropping the root frees the whole tree. The leaves under 98 and 320 are not drawn.7.5 Layout
An enum is stored as a tag, a small integer that says which variant, followed by room for the largest variant’s fields. The compiler may do better when a field type has values that can never occur.
fn row(name: &str, bytes: usize) {
println!("{name:<22}{bytes:>3}");
}
fn main() {
row("u32", size_of::<u32>());
row("Option<u32>", size_of::<Option<u32>>()); // a tag beside the u32
row("&u32", size_of::<&u32>());
row("Option<&u32>", size_of::<Option<&u32>>()); // None is the null address
row("Box<u32>", size_of::<Box<u32>>());
row("Option<Box<u32>>", size_of::<Option<Box<u32>>>());
row("Shape", size_of::<Shape>()); // three f64s and a tag
row("Option<bool>", size_of::<Option<bool>>()); // bool uses 2 of 256 values
row("Result<u32, String>", size_of::<Result<u32, String>>());
}
$ rustc --edition 2021 -O -o sizes sizes.rs && ./sizes
u32 4
Option<u32> 8
&u32 8
Option<&u32> 8
Box<u32> 8
Option<Box<u32>> 8
Shape 32
Option<bool> 1
Result<u32, String> 24
Option<u32> needs a tag, since all bit patterns of a u32 are values; padded to the alignment of the u32, 8 bytes. Shape holds a tag and its largest variant, the triangle’s three sides. Option<&u32> needs no tag: a reference is never null, so the address 0 is free to mean None.The last layout is a guarantee, not an accident: the standard library documents that Option<T> has the same size as T when T is a reference, a Box, a function pointer or a non-zero integer, with None represented by all zero bits. An optional reference therefore costs exactly what a C pointer that may be NULL costs, and the check the C programmer may forget is required by the type. The same reasoning gives Option<bool> one byte: a bool uses 2 of the 256 patterns of its byte, and None takes a third.
In practice — Error types in practice
Give each module its own error enum, with one variant per failure the caller may want to distinguish, and data (a line number, a file name) for the message. Implement std::fmt::Display for the message and From for the errors of the lower layers, so that ? converts them. Keep unwrap and expect for conditions that are bugs if false, and say why in the expect message.
7.6 Exercises
Exercise 7.1 ★
Predict the five lines, then check them in the solution. What changes if the arm 0 => "zero" is moved just after 1..=9? And if it is moved after the wildcard _?
fn kind(n: i32) -> &'static str {
match n {
0 => "zero",
x if x < 0 => "negative",
1..=9 => "digit",
10 | 100 | 1000 => "power of ten",
_ => "other",
}
}
fn main() {
for n in [7, -3, 100, 0, 12] {
let pair = (n % 2 == 0, n > 5);
let size = match pair {
(true, true) => "even and large",
(true, false) => "even and small",
(false, large) => if large { "odd and large" } else { "odd and small" },
};
println!("{n}: {}, {size}", kind(n));
}
}
Solution
Solution of Exercise 7.1.
$ rustc --edition 2021 -O -o exo_match exo_match.rs && ./exo_match
7: digit, odd and large
-3: negative, odd and small
100: power of ten, even and large
0: zero, even and small
12: other, even and large
fails 0, then passes the guard. 12 fails every literal and range and falls to _. In the second match, (false, large) binds the second component, so one arm covers both odd cases. Moving 0 => "zero" after 1..=9 changes nothing: no earlier arm matches 0 (the guard x < 0 is false for it). Moved after _, it can never be reached: the compiler warns unreachable pattern and 0 prints other.
Exercise 7.2 ★
The library added the variant Lost to LoanState, and the program no longer compiles. Fix fine_cents (a lost book costs 2000 cents). Then explain what would have happened if the last arm had been _ => 0.
#[allow(dead_code)]
enum LoanState {
Out { days: u32 },
Returned,
Lost, // the new variant
}
fn fine_cents(s: &LoanState) -> u32 {
match s {
LoanState::Out { days } if *days > 21 => 10 * (days - 21),
LoanState::Out { .. } => 0,
LoanState::Returned => 0,
}
}
Lost code/bachelor-2/07-rust-enums-and-errors/listings/exo_new_variant.rsSolution
Solution of Exercise 7.2.
error[E0004]: non-exhaustive patterns: `&LoanState::Lost` not covered
--> exo_new_variant.rs:11:11
|
11 | match s {
| ^ pattern `&LoanState::Lost` not covered
...
7 | Lost, // the new variant
| ---- not covered
Add the arm LoanState::Lost => 2000. With a last arm _ => 0 in place of Returned, the program would have compiled, and a lost book would have cost nothing: the wildcard silently took the variant written after it. Exhaustiveness checks only the variants that are not already covered by a wildcard.
Exercise 7.3 ★
Write checked_div(a: i32, b: i32) -> Option<i32>, which returns None when the quotient does not exist or does not fit, and mean(xs: &[f64]) -> Option<f64>. In which two cases does a / b panic in Rust?
Solution
Solution of Exercise 7.3.
pub fn checked_div(a: i32, b: i32) -> Option<i32> {
match (a, b) {
(_, 0) => None, // division by zero
(i32::MIN, -1) => None, // the quotient 2^31 does not fit in an i32
_ => Some(a / b),
}
}
pub fn mean(xs: &[f64]) -> Option<f64> {
if xs.is_empty() {
None
} else {
Some(xs.iter().sum::<f64>() / xs.len() as f64)
}
}
None code/bachelor-2/07-rust-enums-and-errors/exercises/checked.rsa / b panics when b == 0 (attempt to divide by zero) and when a == i32::MIN and b == -1: the quotient does not fit, and Rust panics on this overflow in every build mode. The standard library already has i32::checked_div, with the same contract.
Exercise 7.4 ★
Using Proposition 7.3, count the values of: (bool, bool, u8); Option<Option<bool>>; Result<bool, Option<u8>>; an enum with the variants Red, Amber, Green and Flashing(bool); and [bool; 2]. Which of them could share the same set of values, up to renaming?
Solution
Solution of Exercise 7.4.
(bool, bool, u8): . Option<Option<bool>>: . Result<bool, Option<u8>>: . The traffic light: . [bool; 2]: . Option<Option<bool>> and [bool; 2] both have 4 values, so a bijection exists, for example None, Some(None), Some(Some(false)), Some(Some(true)) to [false, false], … Equal counts say only that some renaming exists; which one is meant is the programmer’s choice.
Exercise 7.5 ★★
For each of the three calls, say where total returns and which lines are printed, then check against the output in the solution.
fn parse_pages(s: &str) -> Result<u32, String> {
let n: u32 = s.trim().parse().map_err(|_| format!("not a number: {s:?}"))?;
if n == 0 {
return Err("a book has pages".to_string());
}
Ok(n)
}
fn total(a: &str, b: &str) -> Result<u32, String> {
let x = parse_pages(a)?;
println!(" first is {x}");
let y = parse_pages(b)?;
println!(" second is {y}");
Ok(x + y)
}
fn main() {
println!("{:?}", total("65", " 133"));
println!("{:?}", total("sixty", "133"));
println!("{:?}", total("65", "0"));
}
? in a row code/bachelor-2/07-rust-enums-and-errors/listings/exo_question.rsSolution
Solution of Exercise 7.5.
$ rustc --edition 2021 -O -o exo_question exo_question.rs && ./exo_question
first is 65
second is 133
Ok(198)
Err("not a number: \"sixty\"")
first is 65
Err("a book has pages")
First call: both ? pass (trim removes the space), both lines printed, Ok(198). Second: the first ? in total returns the Err built by map_err, before any print. Third: the first value prints, then parse_pages("0") returns its own Err by return, and the second ? returns it from total.
Exercise 7.6 ★★
The program stops at the third line. Explain the message, and rewrite the loop so that a bad line is reported with its number and skipped, using Option and Result instead of unwrap.
let lines = ["Mill Lane,12", "Quay Street,3", "Bridge Way", "Castle Row,8"];
let mut sum = 0;
for line in lines {
let (street, number) = line.split_once(',').unwrap();
let n: u32 = number.parse().unwrap();
println!("{street}: {n}");
sum += n;
}
println!("sum {sum}");
unwraps code/bachelor-2/07-rust-enums-and-errors/listings/exo_unwrap.rsMill Lane: 12
Quay Street: 3
panicked at exo_unwrap.rs:11:53:
called `Option::unwrap()` on a `None` value
[exit status 101]
Solution
Solution of Exercise 7.6.
"Bridge Way".split_once(',') is None: there is no comma. unwrap on None panics, at line 11, column 53, the column of unwrap. The loop becomes for (i, line) in lines.iter().enumerate(). A let-else, let Some((street, number)) = line.split_once(',') else {...}, whose else block reports line 3: no comma and continues the loop, replaces the first unwrap; and match number.parse::<u32>() adds n on Ok(n) and reports the parse error on Err(e). The sum is then 23, over the three good lines, and the bad one is named.
Exercise 7.7 ★★
Write an enum Json for JSON-like values (null, booleans, numbers, strings, arrays, objects with keys in order) and a method to_text that prints a value on one line, escaping ", the backslash and the newline in strings. Test it on a book record whose title contains quotation marks.
Solution
Solution of Exercise 7.7.
pub enum Json {
Null,
Bool(bool),
Num(f64),
Str(String),
Arr(Vec<Json>),
Obj(Vec<(String, Json)>), // keys in insertion order
}
pub fn write(&self, out: &mut String) {
match self {
Json::Null => out.push_str("null"),
Json::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
Json::Num(x) => out.push_str(&x.to_string()),
Json::Str(s) => quote(s, out),
Json::Arr(items) => {
out.push('[');
for (i, v) in items.iter().enumerate() {
if i > 0 {
The arrays and objects recurse through write, which appends to one String instead of building and concatenating a string per node. quote escapes the three characters. The test in tests/enums prints a book record with The "Silent" Code as its title and compares the whole line.
Exercise 7.8 ★★
The mirror image of a tree swaps the left and right subtrees of every node. Define mirror on the Tree of Listing 7.7 and prove by structural induction that mirror(mirror(t)) == t for every tree. Prove also that the in-order walk of mirror(t) is the in-order walk of t reversed.
Solution
Solution of Exercise 7.8.
mirror(Leaf) = Leaf; mirror(Node(l, k, r)) = Node(mirror(r), k, mirror(l)). By structural induction. Leaf: . Node, with for mirror and for Node:
by the hypothesis on and . For the walk, write for the in-order walk and for a reversed sequence: is empty, and
by the hypothesis and the rule . The crate tests the first property on 200 random trees.
Exercise 7.9 ★★
Write enum List<T> { Nil, Cons(T, Box<List<T>>) } with from_vec, len, rev and map. Write len and rev with loops: why does rev need no clone of the elements? Test that l.rev().rev() == l.
Solution
Solution of Exercise 7.9.
pub fn rev(self) -> List<T> {
let mut out = Nil;
let mut cur = self;
while let Cons(x, rest) = cur {
out = Cons(x, Box::new(out)); // move each node's value to the front of out
cur = *rest;
}
out
}
rev takes the list by value: it owns every node, so while let Cons(x, rest) = cur moves x out and cur = *rest moves the rest out of its box; each value goes into a new node with no copy. len and rev are loops, so a long list does not grow the stack. map recurses, one frame per node, which is fine for the tests’ lists; note that dropping a very long list recurses too, as the Stack of Chapter 6 showed.
Exercise 7.10 ★★★
Extend the expression type to f64 with Sin and Cos, and write derive, which returns the derivative by the sum, product and chain rules, and simplify. Test derive on 500 random expressions against the central difference , with a tolerance you justify, and check that simplification never makes an expression larger.
Solution
Solution of Exercise 7.10.
pub fn derive(&self) -> F {
match self {
Num(_) => Num(0.0),
X => Num(1.0),
Add(p, q) => Add(b(p.derive()), b(q.derive())),
// product rule: (pq)' = p'q + pq'
Mul(p, q) => Add(b(Mul(b(p.derive()), q.clone())),
b(Mul(p.clone(), b(q.derive())))),
// chain rule: (sin p)' = cos(p) p', (cos p)' = -sin(p) p'
Sin(p) => Mul(b(Cos(p.clone())), b(p.derive())),
Cos(p) => Mul(b(Mul(b(Num(-1.0)), b(Sin(p.clone())))), b(p.derive())),
}
}
The central difference has error about from the formula and about from rounding, with ; for and functions of moderate size both are below , so a relative tolerance of leaves a wide margin while still catching a wrong sign or a missing factor (those give errors of order 1). The test checks 500 random functions at five points. simplify never grows a tree: each arm returns either a node built from the simplified children, by induction no larger, or a child, or a single number, all no larger than the original.
Exercise 7.11 ★★★
(a) Prove that eval terminates on every expression with Proposition 7.10, and bound the number of calls by the number of nodes. (b) Complete the proof of Theorem 7.11: the Mul case, arm by arm. (c) Which arm would break the theorem if the values were f64? Give an expression.
Solution
Solution of Exercise 7.11.
(a) eval recurses only on the fields of the matched variant, and its other operations, additions and multiplications, terminate: by Proposition 7.10 it terminates. It is called exactly once on each node, by induction: and , the number of nodes. (b) Mul(a, b), with and . Arm 1, both numbers: , the product. Arm 2, a zero: , and in the ring. Arm 3, a one: the other side, and . Arm 4: Mul(S(a), S(b)), of value . Every arm gives . (c) The zero arm: with f64, Mul(Num(0), Mul(X, X)) at is , which is NaN, but simplifies to 0.
Exercise 7.12 ★★★
A configuration file has lines key = value, comments after a hash sign, and blank lines. Write parse(text) -> Result<BTreeMap<String, String>, ConfigError>, where ConfigError carries the line number and a Kind: no =, empty key, a key set twice, a value that starts like a number but is not one. Implement Display so that e.to_string() gives messages such as line 3: a set twice.
Solution
Solution of Exercise 7.12.
pub fn parse(text: &str) -> Result<BTreeMap<String, String>, ConfigError> {
let mut map = BTreeMap::new();
for (i, raw) in text.lines().enumerate() {
let line = i + 1;
let err = |kind| ConfigError { line, kind };
let content = raw.split('#').next().unwrap_or("").trim(); // drop a comment
if content.is_empty() {
continue;
}
let (k, v) = content.split_once('=').ok_or(err(Kind::NoEquals))?;
let (k, v) = (k.trim(), v.trim());
if k.is_empty() {
return Err(err(Kind::EmptyKey));
}
if v.starts_with(|c: char| c.is_ascii_digit() || c == '-')
&& v.parse::<f64>().is_err() {
return Err(err(Kind::BadNumber(v.to_string())));
}
if map.insert(k.to_string(), v.to_string()).is_some() {
return Err(err(Kind::Duplicate(k.to_string())));
}
}
Ok(map)
}
The closure err builds an error at the current line, so each check is one line. ok_or turns the Option of split_once into a Result for ?. insert returns the previous value, so a duplicate key is detected without a second lookup. The tests check each kind and the Display message.
7.7 Problem: Reading the weather station logs
Problem 7.1
Weekend problem — Reading the weather station logs
The town’s two stations, Hilltop and Riverside, log a line a day each for 2025. The log is known to hold defects: some temperatures are missing, some are the stations’ code for no measurement, and a line may be repeated. This problem reads it with the types of this chapter and checks that no defect is accepted silently.
Part I — Types for readings.
- Why is
Stationan enum rather than aString? What does derivingPartialOrdandOrdgive it? Readingis a product of five fields. Why istemp_canf64and not anOption<f64>?- List the variants of
LineErrorand the line defect each one describes. - How many values has
Station? AndOption<Station>? How many bytes would you expect for each? - Why is
-99.0detected innumberrather than by the caller? - What would a C version of
parse_linereturn, and how would the caller tell the five errors apart?
Part II — Parsing with Result.
#[derive(Debug)]
pub enum LogError {
Io(std::io::Error), // the file could not be read
NoHeader,
}
impl From<std::io::Error> for LogError {
fn from(e: std::io::Error) -> Self {
LogError::Io(e) // lets ? turn an io::Error into a LogError
}
pub fn read_log(path: &str) -> Result<Log, LogError> {
let text = std::fs::read_to_string(path)?; // an io::Error becomes a LogError here
let mut lines = text.lines();
if lines.next() != Some("date,station,temp_c,rain_mm,wind_kmh") {
return Err(LogError::NoHeader);
}
let mut log = Log { readings: Vec::new(), rejected: Vec::new(), duplicates: Vec::new() };
let mut seen = HashSet::new();
for (i, line) in lines.enumerate() {
let number = i + 2; // the header is line 1
match parse_line(line) {
Ok(r) if !seen.insert((r.date.clone(), r.station)) => log.duplicates.push(number),
Ok(r) => log.readings.push(r),
Err(e) => log.rejected.push((number, e)),
}
}
Ok(log)
read_log code/bachelor-2/07-rust-enums-and-errors/listings/weather.rs- In
parse_line, which fields are still read whentemp_cis missing? read_to_string(path)?returns astd::io::Error, yetread_logreturnsLogError. Which line makes this compile?- Why does
read_logusematchonparse_lineinstead of?? - The first
Okarm has a guard. Explain it, and why its order with the secondOkarm matters. - Which line of Output 7.6 comes from
LogError::Io, and through how many functions did the error travel? - Add a variant for a date that is not of the form
YYYY-MM-DD. Whichmatches must change?
Part III — A tree of monthly aggregates.
- Store, for each pair (station, month), the number of readings, their sum, minimum and maximum, in a
BTreeMap<(Station, u32), Agg>. Why does a tuple key with a derived order give the months of Hilltop first? - Use the
entryAPI,and_modifyandor_insert, to update the tree in one lookup per reading. - How many keys does the tree have, and how many readings in all?
- Riverside has 31 lines in June 2025. How many readings does its June aggregate count, and why?
- Which months lose a reading to a missing temperature or an error code?
- Why must the mean be computed from the sum and the count rather than kept as a running mean?
Part IV — Every defect accounted for.
- Check that the counts of Output 7.6 add up to the 731 lines of data.
- Which test in
tests/enumswould fail if a missing temperature were read as 0.0? - How would the C function of the opening treat the two error codes? And the missing fields?
- The duplicate is identical to the earlier line. Should it be rejected or merged? Justify.
- A new defect type appears next year: a temperature written with a comma,
3,9. What happens to such a line with the current code, and is it accepted silently? - State the result of the problem: every planted defect found, with its count, and none accepted silently.
Solution
Solution of Problem 7.1.
1. A misspelt station cannot be stored, and every match on a station is checked for both. The derived order is the order of declaration, Hilltop before Riverside, so stations can be sorted and used in a BTreeMap key.
2. A Reading is built only when all five fields parsed; a line without a temperature becomes a LineError instead. The type says: every reading has a temperature.
3. FieldCount: not five fields. UnknownStation: a name other than the two. Missing: an empty field. BadNumber: text that is not a number. ErrorCode: the value .
4. 2 and 3 values. One byte each: the tag of Station uses 2 of the 256 patterns of its byte, and None takes a third, as for Option<bool>.
5. It is the same rule for every field: written once in number, it cannot be forgotten by one of the three callers.
6. An int status and the reading through a pointer, with codes such as to by convention; the caller can ignore the status and read an unfilled struct, and nothing ties the code to the data it describes (a field name, the bad text).
7. None after it: the ? on temp_c returns, so rain and wind are not read. The date and the station were read before.
8. impl From<std::io::Error> for LogError: ? calls From::from on the error.
9. A bad line must not end the reading: ? would return at the first rejected line and lose the whole log. The match records the error and continues.
10. seen.insert returns false when the pair was already there, so the guard holds exactly for a repeated reading, which goes to duplicates; the call also records a new pair. If the plain Ok(r) arm came first, it would take every reading and no duplicate would be found.
11. cannot read wether.csv. The io::Error is made inside read_to_string, converted and returned by the ? of read_log, and matched in main: through read_log, from the standard library to main.
12. A variant BadDate(String), built in parse_line. No match on LineError exists in the program (it is printed with Debug, derived), so none must change; a hand-written Display, as in Exercise 7.12, would have to, and the compiler would say so.
13. Tuples compare lexicographically: the station first, then the month, and Hilltop is smaller.
14.
let mut tree: BTreeMap<(Station, u32), Agg> = BTreeMap::new(); // balanced, in key order
for r in readings {
let month: u32 = r.date[5..7].parse().expect("dates are YYYY-MM-DD");
tree.entry((r.station, month))
.and_modify(|a| {
a.n += 1;
a.sum += r.temp_c;
a.min = a.min.min(r.temp_c);
a.max = a.max.max(r.temp_c);
})
.or_insert(Agg { n: 1, sum: r.temp_c, min: r.temp_c, max: r.temp_c });
}
tree
15. 24 keys, 2 stations times 12 months, and 722 readings, those kept by read_log.
16. 30: June has 30 days, and the 31st line is the duplicate of 14 June, set aside before the aggregation.
17. Hilltop: January, August and December. Riverside: January, April, November (two) and December. Eight readings in all, those of the eight rejected lines.
18. Sum and count are what combine: two aggregates merge by adding them, and the mean is derived at the end. A running mean must be rescaled at each reading, with a rounding each time, and cannot be merged without the counts anyway.
19. .
20. every_planted_defect: it expects 722 readings and six Missing; with zeros there would be 728 readings and no Missing.
21. becomes tenths, a valid answer accepted silently. A missing field gives , which the caller cannot tell from °C.
22. Rejected from the readings but reported: the two lines are identical, so merging would change nothing in the data, but counting it twice would bias June’s mean towards 14 June, and a repeated line is a symptom of the logger worth reporting.
23. 3,9 splits into two fields: the line has six, and is rejected as FieldCount(6). Not accepted silently, though the error names the symptom rather than the cause.
24. Every planted defect found — six missing temperatures, two error codes, one duplicate — and none accepted silently: the 731 lines are 722 readings, 8 rejected lines with their reasons, and 1 duplicate.