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