re-do deepaksirone's fix on the actual source file
[rust-101.git] / workspace / src / part10.rs
1 // Rust-101, Part 10: Closures
2 // ===========================
3
4 use std::fmt;
5 use part05::BigInt;
6
7
8 // So, let us define a trait that demands that the type provides some method `do_action` on digits.
9 trait Action {
10     fn do_action(&mut self, digit: u64);
11 }
12
13 // Now we can write a function that takes some `a` of a type `A` such that we can call `do_action` on `a`, passing it every digit.
14 impl BigInt {
15     fn act_v1<A: Action>(&self, mut a: A) {
16         for digit in self {
17             unimplemented!()
18         }
19     }
20 }
21
22 struct PrintWithString {
23     prefix: String,
24 }
25
26 impl Action for PrintWithString {
27     // Here we perform the actual printing of the prefix and the digit. We're not making use of our ability to
28     // change `self` here, but we could replace the prefix if we wanted.
29     fn do_action(&mut self, digit: u64) {
30         unimplemented!()
31     }
32 }
33
34 // Finally, this function takes a `BigInt` and a prefix, and prints the digits with the given prefix.
35 fn print_with_prefix_v1(b: &BigInt, prefix: String) {
36     let my_action = PrintWithString { prefix: prefix };
37     b.act_v1(my_action);
38 }
39
40 // Here's a small main function, demonstrating the code above in action. Remember to edit `main.rs` to run it.
41 pub fn main() {
42     let bignum = BigInt::new(1 << 63) + BigInt::new(1 << 16) + BigInt::new(1 << 63);
43     print_with_prefix_v1(&bignum, "Digit: ".to_string());
44 }
45
46 // ## Closures
47
48 // This defines `act` very similar to above, but now we demand `A` to be the type of a closure that mutates its borrowed environment,
49 // takes a digit, and returns nothing.
50 impl BigInt {
51     fn act<A: FnMut(u64)>(&self, mut a: A) {
52         for digit in self {
53             // We can call closures as if they were functions - but really, what's happening here is translated to essentially what we wrote above, in `act_v1`.
54             unimplemented!()
55         }
56     }
57 }
58
59 // Now that we saw how to write a function that operates on closures, let's see how to write a closure.
60 pub fn print_with_prefix(b: &BigInt, prefix: String) {
61     b.act(|digit| println!("{}{}", prefix, digit) );
62 }
63 // You can change `main` to call this function, and you should notice - nothing, no difference in behavior.
64 // But we wrote much less boilerplate code!
65
66 // Remember that we decided to use the `FnMut` trait above? This means our closure could actually mutate its environment.
67 // For example, we can use that to count the digits as they are printed.
68 pub fn print_and_count(b: &BigInt) {
69     let mut count: usize = 0;
70     b.act(|digit| { println!("{}: {}", count, digit); count = count +1; } );
71     println!("There are {} digits", count);
72 }
73
74 // ## Fun with iterators and closures
75
76 // Let's say we want to write a function that increments every entry of a `Vec` by some number, then looks for numbers larger than some threshold, and prints them.
77 fn inc_print_even(v: &Vec<i32>, offset: i32, threshold: i32) {
78     for i in v.iter().map(|n| *n + offset).filter(|n| *n > threshold) {
79         println!("{}", i);
80     }
81 }
82
83 // Sometimes it is useful to know both the position of some element in a list, and its value. That's where the `enumerate` function helps.
84 fn print_enumerated<T: fmt::Display>(v: &Vec<T>) {
85     for (i, t) in v.iter().enumerate() {
86         println!("Position {}: {}", i, t);
87     }
88 }
89
90 // And as a final example, one can also collect all elements of an iterator, and put them, e.g., in a vector.
91 fn filter_vec_by_divisor(v: &Vec<i32>, divisor: i32) -> Vec<i32> {
92     unimplemented!()
93 }
94
95 // **Exercise 10.1**: Look up the [documentation of `Iterator`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html) to learn about more functions
96 // that can act on iterators. Try using some of them. What about a function that sums the even numbers of an iterator? Or a function that computes the
97 // product of those numbers that sit at odd positions? A function that checks whether a vector contains a certain number? Whether all numbers are
98 // smaller than some threshold? Be creative!
99