add all the parts in workspace's main.rs
[rust-101.git] / workspace / src / part01.rs
1 // Rust-101, Part 01: Expressions, Inherent methods
2 // ================================================
3
4 // For Rust to compile this file, make sure to enable the corresponding line
5 // in `main.rs` before going on.
6
7
8 // ## Expression-based programming
9 fn sqr(i: i32) -> i32 { i * i }
10
11 // Conditionals are also just expressions. You can compare this to the ternary `? :` operator
12 // from languages like C.
13 fn abs(i: i32) -> i32 { if i >= 0 { i } else { -i } }
14
15 enum NumberOrNothing {
16     Number(i32),
17     Nothing
18 }
19 use self::NumberOrNothing::{Number,Nothing};
20 fn number_or_default(n: NumberOrNothing, default: i32) -> i32 {
21     match n {
22         Nothing => default,
23         Number(n) => n,
24     }
25 }
26
27 // Let us now refactor `vec_min`.
28 fn vec_min(v: Vec<i32>) -> NumberOrNothing {
29     fn min_i32(a: i32, b: i32) -> i32 {
30         unimplemented!()
31     }
32
33     let mut min = Nothing;
34     for e in v {
35         unimplemented!()
36     }
37     min
38 }
39
40 // Now that's already much shorter! Make sure you can go over the code above and actually understand
41 // every step of what's going on.
42
43 // ## Inherent implementations
44 impl NumberOrNothing {
45     fn print(self) {
46         match self {
47             Nothing => println!("The number is: <nothing>"),
48             Number(n) => println!("The number is: {}", n),
49         };
50     }
51 }
52
53 // With our refactored functions and methods, `main` now looks as follows:
54 fn read_vec() -> Vec<i32> {
55     vec![18,5,7,2,9,27]
56 }
57 pub fn main() {
58     let vec = read_vec();
59     let min = vec_min(vec);
60     unimplemented!()
61 }
62 // You will have to replace `part00` by `part01` in the `main` function in
63 // `main.rs` to run this code.
64
65 // **Exercise 01.1**: Write a funtion `vec_sum` that computes the sum of all values of a `Vec<i32>`.
66
67 // **Exercise 01.2**: Write a function `vec_print` that takes a vector and prints all its elements.
68