re-do deepaksirone's fix on the actual source file
[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. This is comparable 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 // It is even the case that blocks are expressions, evaluating to the last expression they contain.
28 fn compute_stuff(x: i32) -> i32 {
29     let y = { let z = x*x; z + 14 };
30     y*y
31 }
32
33 // Let us now refactor `vec_min`.
34 fn vec_min(v: Vec<i32>) -> NumberOrNothing {
35     fn min_i32(a: i32, b: i32) -> i32 {
36         unimplemented!()
37     }
38
39     let mut min = Nothing;
40     for e in v {
41         unimplemented!()
42     }
43     min
44 }
45
46 // Now that's already much shorter! Make sure you can go over the code above and actually understand
47 // every step of what's going on.
48
49 // ## Inherent implementations
50 impl NumberOrNothing {
51     fn print(self) {
52         match self {
53             Nothing => println!("The number is: <nothing>"),
54             Number(n) => println!("The number is: {}", n),
55         };
56     }
57 }
58
59 // With our refactored functions and methods, `main` now looks as follows:
60 fn read_vec() -> Vec<i32> {
61     vec![18,5,7,2,9,27]
62 }
63 pub fn main() {
64     let vec = read_vec();
65     let min = vec_min(vec);
66     unimplemented!()
67 }
68 // You will have to replace `part00` by `part01` in the `main` function in
69 // `main.rs` to run this code.
70
71 // **Exercise 01.1**: Write a function `vec_sum` that computes the sum of all values of a `Vec<i32>`.
72
73 // **Exercise 01.2**: Write a function `vec_print` that takes a vector and prints all its elements.
74