refine part 00
[rust-101.git] / src / part00.rs
1 // Rust-101, Part 00: Algebraic datatypes, expressions
2 // ===================================================
3
4 // As our first piece of Rust code, we want to write a function that computes the
5 // minimum of a list. We are going to make use of the standard library, so let's import that:
6
7 use std;
8
9 // Let us start by thinking about the *type* of our function. Rust forces us to give the types of
10 // all arguments, and the return type, before we even start writing the body. In the case of our minimum
11 // function, we may be inclined to say that it returns a number. But then we would be in trouble: What's
12 // the minimum of an empty list? The type of the function says we have to return *something*.
13 // We could just choose 0, but that would be kind of arbitrary. What we need
14 // is a type that is "a number, or nothing". Such a type (of multiple exclusive options)
15 // is called an "algebraic datatype", and Rust lets us define such types with the keyword `enum`.
16 // Coming from C(++), you can think of such a type as a `union`, together with a field that
17 // stores the variant of the union that's currently used.
18
19 enum NumberOrNothing {
20     Number(i32),
21     Nothing
22 }
23
24 // Notice that `i32` is the type of (signed, 32-bit) integers. To write down the type of
25 // the minimum function, we need just one more ingredient: `Vec<i32>` is the type of
26 // (growable) arrays of numbers, and we will use that as our list type.
27 // Observe how in Rust, the return type comes *after* the arguments.
28
29 fn vec_min_try1(vec: Vec<i32>) -> NumberOrNothing {
30     // First, we need some variable to store the minimum as computed so far.
31     // Since we start out with nothing computed, this will again be a 
32     // "number or nothing":
33     let mut min = NumberOrNothing::Nothing;
34     // We do not have to write a type next to `min`, Rust can figure that out automatically
35     // (a bit like `auto` in C++11). Also notice the `mut`: In Rust, variables are
36     // immutable per default, and you need to tell Rust if you want
37     // to change a variable later.
38
39     // Now we want to *iterate* over the list. Rust has some nice syntax for
40     // iterators:
41     for el in vec {
42         // So `el` is al element of the list. We need to update `min` accordingly, but how do we get the current
43         // number in there? This is what pattern matching can do:
44         match min {
45             NumberOrNothing::Nothing => {
46                 // In this case (*arm*) of the `match`, `min` is currently nothing, so let's just make it the number `el`.
47                 min = NumberOrNothing::Number(el);
48             },
49             NumberOrNothing::Number(n) => {
50                 // In this arm, `min` is currently the number `n`, so let's compute the new minimum and store it.
51                 let new_min = std::cmp::min(n, el);
52                 min = NumberOrNothing::Number(new_min);
53             }
54         }
55     }
56     // Finally, we return the result of the computation.
57     return min;
58 }
59
60 // Phew. We wrote our first Rust function! But all this `NumberOrNothing::` is getting kind of
61 // ugly. Can't we do that nicer? Indeed, we can: The following line tells Rust to take
62 // the constructors of `NumberOrNothing` into the local namespace:
63 use self::NumberOrNothing::{Number,Nothing};
64 // Try moving that above the function, and removing all the occurrences `NumberOrNothing::`.
65 // Things should still compile, now being much less verbose!
66
67 // There is more prettification we can do. To understand how, it is important to
68 // understand that Rust is an "expression-based" language. This means that most of the
69 // terms you write down are not just *statements* (executing code), but *expressions*
70 // (returning a value). This applies even to the body of entire functions!
71
72 // For example, consider `sqr`:
73 fn sqr(i: i32) -> i32 { i * i }
74 // Between the curly braces, we are giving the *expression* that computes the return value.
75 // So we can just write `i * i`, the expression that returns the square if `i`!
76 // This is very close to how mathematicians write down functions (but with more types).
77
78 // Conditionals are also just expressions. You can compare this to the ternary `? :` operator
79 // from languages like C.
80 fn abs(i: i32) -> i32 { if i >= 0 { i } else { -i } }
81
82 // And the same applies to case distinction with `match`: Every `arm` of the match
83 // gives the expression that is returned in the respective case.
84 fn number_or_default(n: NumberOrNothing, default: i32) -> i32 {
85     match n {
86         Nothing => default,
87         Number(n) => n,
88     }
89 }
90
91 // With this fresh knowledge, let us now refactor `vec_min`.
92 fn vec_min(v: Vec<i32>) -> NumberOrNothing {
93     let mut min = Nothing;
94     for e in v {
95         // First of all, notice that all we do here is compute a new value for `min`, and that it
96         // will always end up being `Number` rather than `Nothing`. In Rust, the structure of the code
97         // can express this uniformity as follows:
98         min = Number(match min {
99             Nothing => e,
100             Number(n) => std::cmp::min(n, e)
101         });
102     }
103     // The `return` keyword exists in Rust, but it is rarely used. Instead, we typically
104     // make use of the fact that the entire function body is an expression, so we can just
105     // write down the desired return value.
106     min
107 }
108
109 // Now that's already much shorter! Make sure you can go over the code above and actually understand
110 // every step of what's going on.
111
112 // To call this function, we now just need a list. Of course, ultimately we want to ask the user for
113 // a list of numbers, but for now, let's just hard-code something:
114
115 fn read_vec() -> Vec<i32> {
116     vec![18,5,7,1,9,27]
117     // `vec!` is a *macro* (as you can tell from the `!`) that constructs a constant `Vec` with the given
118     // elements.
119 }
120
121 // Finally, let's call our functions and run the code!
122 // But, wait, we would like to actually see something, so we need to print the result.
123 // Of course Rust can print numbers, but after calling `vec_min`, we have a `NumberOrNothing`.
124 // So let's write a small helper function that prints such values.
125
126 fn print_number_or_nothing(n: NumberOrNothing) {
127     match n {
128         Nothing => println!("The number is: <nothing>"),
129         Number(n) => println!("The number is: {}", n),
130     };
131 }
132
133 // Putting it all together:
134
135 pub fn part_main() {
136     let vec = read_vec();
137     let min = vec_min(vec);
138     print_number_or_nothing(min);
139 }
140
141 // Now try `cargo run` on the console to run above code.
142
143 // Yay, it said "1"! That's actually the right answer. Okay, we could have
144 // computed that ourselves, but that's besides the point. More importantly:
145 // You completed the first part of the course.
146
147 // [index](main.html) | previous | [next](part01.html)