|
| 1 | +//! Lab (answer) |
| 2 | +//! Iterators |
| 3 | +//! |
| 4 | +//! Fix all the compile errors below and/or follow the hints provided |
| 5 | +//! |
| 6 | +
|
1 | 7 | fn main() { |
2 | | - println!("TBD"); |
| 8 | + // TASK 1 - Looping via Array Indices |
| 9 | + // Hint: Print ALL values. Check the output to verify you printed all elements |
| 10 | + let array = [2, 4, 6, 8]; |
| 11 | + for idx in 0..4 { |
| 12 | + println!("{}", array[idx]); |
| 13 | + } |
| 14 | + |
| 15 | + // TASK 2 - Using Our Iterator |
| 16 | + // Hint: The 'for' loop calls '.next()' under the hood |
| 17 | + struct SliceIter<'s> { |
| 18 | + slice: &'s [i32], |
| 19 | + idx: usize, |
| 20 | + } |
| 21 | + impl<'s> Iterator for SliceIter<'s> { |
| 22 | + type Item = &'s i32; |
| 23 | + fn next(&mut self) -> Option<Self::Item> { |
| 24 | + if self.idx == self.slice.len() { |
| 25 | + None |
| 26 | + } else { |
| 27 | + let next = &self.slice[self.idx]; |
| 28 | + self.idx += 1; |
| 29 | + Some(next) |
| 30 | + } |
| 31 | + } |
| 32 | + } |
| 33 | + let numbers = [10, 20, 30]; |
| 34 | + let iter = SliceIter { |
| 35 | + slice: &numbers, |
| 36 | + idx: 0, |
| 37 | + }; |
| 38 | + for my_iter in iter { |
| 39 | + println!("The number is: {}", my_iter); |
| 40 | + } |
| 41 | + |
| 42 | + // TASK 3 - Getting an Iterator - 'iter()' |
| 43 | + // Hint: Collections themselves are not iterators |
| 44 | + // Using 'iter()' does not consume the collection |
| 45 | + let numbers_2 = vec![10, 20, 30]; |
| 46 | + for n in numbers_2.iter() { |
| 47 | + println!("{n}"); |
| 48 | + } |
| 49 | + println!("Done printing {} items.", numbers_2.len()); |
| 50 | + |
| 51 | + // TASK 4 - Common Iterator Adapters |
| 52 | + // Hint: 'map' transforms values during iteration, 'filter' selects values matching condition |
| 53 | + fn double(x: &i32) -> i32 { |
| 54 | + x * 2 |
| 55 | + } |
| 56 | + fn is_even(x: &&i32) -> bool { |
| 57 | + **x % 2 == 0 |
| 58 | + } |
| 59 | + let flush = vec![10, 11, 12, 13, 14]; |
| 60 | + |
| 61 | + // Multiply all values by 2 |
| 62 | + for elem in flush.iter().map(double) { |
| 63 | + println!("Value multiplied by 2 is: {elem}"); |
| 64 | + } |
| 65 | + // Print only values divisible by 2 |
| 66 | + for elem in flush.iter().filter(is_even) { |
| 67 | + println!("This value is divisible by 2: {elem}"); |
| 68 | + } |
| 69 | + |
| 70 | + // TASK 5 - Common Consumers |
| 71 | + // Hint: 'sum' adds all values and return a single value, 'any' returns True if any value matches condition |
| 72 | + fn is_freezing(temp: &i32) -> bool { |
| 73 | + *temp < 0 |
| 74 | + } |
| 75 | + let hand = [1, 2, 3, 4, 5]; |
| 76 | + // Sum all values into 'Total' |
| 77 | + let total: i32 = hand.iter().sum(); |
| 78 | + println!("The total is: {total}"); |
| 79 | + |
| 80 | + let temperatures = [22, 28, -2, 15, 30]; |
| 81 | + // Print the warning if any temperature is below 0 |
| 82 | + if temperatures.iter().any(is_freezing){ |
| 83 | + println!("Warning: Freezing temperatures detected!"); |
| 84 | + } else { |
| 85 | + println!("All temperatures are above freezing."); |
| 86 | + } |
| 87 | + |
| 88 | + // TASK 6 - Chaining |
| 89 | + // Hint: Chaining allows you to create a new set of data before consuming |
| 90 | + fn is_even_owned(x: &i32) -> bool { |
| 91 | + *x % 2 == 0 |
| 92 | + } |
| 93 | + fn square (x: i32) -> i32 { |
| 94 | + x * x |
| 95 | + } |
| 96 | + let result: i32 = (1..=10) // Range: 1, 2, 3, ..., 10 |
| 97 | + .filter(is_even_owned) // Only select even values |
| 98 | + .map(square) // Square values |
| 99 | + .sum(); // Total: 220 |
| 100 | + println!("Sum of even squares: {}", result); |
| 101 | + |
| 102 | + // TASK 7 - Collecting "Result" |
| 103 | + // Hint: 'collect()' stores results in a collection |
| 104 | + fn parse_i32(s: &str) -> Result<i32, std::num::ParseIntError> { |
| 105 | + s.parse::<i32>() |
| 106 | + } |
| 107 | + let good_strings = vec!["1", "2", "42"]; |
| 108 | + let good_numbers: Result<Vec<i32>, _> = good_strings |
| 109 | + .into_iter() |
| 110 | + .map(parse_i32) |
| 111 | + .collect(); |
| 112 | + println!("good_numbers: {:?}", good_numbers); |
3 | 113 | } |
0 commit comments