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