// then looks for numbers larger than some threshold, and prints them.
fn inc_print_threshold(v: &Vec<i32>, offset: i32, threshold: i32) {
//@ `map` takes a closure that is applied to every element of the iterator. `filter` removes
- //@ elements from the iterator that do not pass the test given by the closure. Since all these
- //@ closures compile down to the pattern described above, there is actually no heap allocation
- //@ going on here. This makes closures very efficient, and it makes optimization fairly
- //@ trivial: The resulting code will look like you hand-rolled the loop in C.
+ //@ elements from the iterator that do not pass the test given by the closure.
+ //@
+ //@ Since all these closures compile down to the pattern described above, there is actually no
+ //@ heap allocation going on here. This makes closures very efficient, and it makes
+ //@ optimization fairly trivial: The resulting code will look like you hand-rolled the loop in
+ //@ C.
for i in v.iter().map(|n| *n + offset).filter(|n| *n > threshold) {
println!("{}", i);
}
// those numbers that sit at odd positions? A function that checks whether a vector contains a
// certain number? Whether all numbers are smaller than some threshold? Be creative!
+// **Exercise 10.2**: We started the journey in Part 02 with `SomethingOrNothing<T>`, and later
+// learned about `Option<T>` in Part 04. `Option<T>` also has a `map` function.
+// [Read its documentation here.](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.map)
+// Which functions in previous parts can you rewrite to use `map` instead?
+// (Hint: read the source code of `map`, and see if the pattern appears in your own code.)
+// Bonus: [`test_invariant` in Part 05](part05.html#section-6) doesn't use `match`,
+// but can you still find a way to rewrite it with `map`?
+
//@ [index](main.html) | [previous](part09.html) | [raw source](workspace/src/part10.rs) |
//@ [next](part11.html)