tuning
[rust-101.git] / workspace / src / part00.rs
1 // ***Remember to enable/add this part in `main.rs`!***
2
3 // Rust-101, Part 00: Algebraic datatypes
4 // ======================================
5
6 // As our first piece of Rust code, we want to write a function that computes the
7 // minimum of a list.
8
9
10 // An `enum` for "a number or nothing" could look as follows:
11 enum NumberOrNothing {
12     Number(i32),
13     Nothing
14 }
15
16 // Observe how in Rust, the return type comes *after* the arguments.
17 fn vec_min(vec: Vec<i32>) -> NumberOrNothing {
18     let mut min = NumberOrNothing::Nothing;
19
20     // Now we want to *iterate* over the list. Rust has some nice syntax for iterators:
21     for el in vec {
22         // So `el` is al element of the list. We need to update `min` accordingly, but how do we get the current
23         // number in there? This is what pattern matching can do:
24         match min {
25             // In this case (*arm*) of the `match`, `min` is currently nothing, so let's just make it the number `el`.
26             NumberOrNothing::Nothing => {
27                 unimplemented!()
28             },
29             // In this arm, `min` is currently the number `n`, so let's compute the new minimum and store it.
30             NumberOrNothing::Number(n) => {
31                 unimplemented!()
32             }
33         }
34     }
35     // Finally, we return the result of the computation.
36     return min;
37 }
38
39 // Now that we reduced the problem to computing the minimum of two integers, let's do that.
40 fn min_i32(a: i32, b: i32) -> i32 {
41     if a < b {
42         unimplemented!()
43     } else {
44         unimplemented!()
45     }
46 }
47
48 // Phew. We wrote our first Rust function! But all this `NumberOrNothing::` is getting kind of
49 // ugly. Can't we do that nicer?
50
51 // Indeed, we can: The following line tells Rust to take
52 // the constructors of `NumberOrNothing` into the local namespace.
53 // Try moving that above the function, and removing all the occurrences `NumberOrNothing::`.
54 use self::NumberOrNothing::{Number,Nothing};
55
56 // To call this function, we now just need a list. Of course, ultimately we want to ask the user for
57 // a list of numbers, but for now, let's just hard-code something.
58
59 fn read_vec() -> Vec<i32> {
60     unimplemented!()
61 }
62
63 // Finally, let's call our functions and run the code!
64 // But, wait, we would like to actually see something, so we need to print the result.
65
66 fn print_number_or_nothing(n: NumberOrNothing) {
67     unimplemented!()
68 }
69
70 // Putting it all together:
71 pub fn main() {
72     let vec = read_vec();
73     let min = vec_min(vec);
74     print_number_or_nothing(min);
75 }
76
77 // You can now use `cargo build` to compile your code. If all goes well, try `cargo run` on the
78 // console to run it.
79
80