Complete these tasks to reinforce what you learned in this module.
Start from let numbers = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];.
Build an iterator chain that keeps only the even numbers, squares each of them, and
collects the results into a Vec<i32>. Print that vector with {:?}. Then compute the
sum of the squared evens and print it on its own line. This is the Rust spelling of the
C# LINQ chain numbers.Where(n => n % 2 == 0).Select(n => n * n) followed by ToList()
and Sum().
numbers.iter().filter(...).map(...).collect(). iter() yields &i32, so
your filter closure pattern can be |&&n| and your map closure |&n| (or use *n).
collect() needs to know the target type — annotate the binding as Vec<i32>. For the
sum, call .iter().sum::<i32>() on the collected vector (or annotate the binding i32).// Task 1: filter even numbers, square them, collect into a Vec, print it and their sum.
// See tasks/TASKS.md.
fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let _ = numbers;
todo!("filter evens, map to squares, collect into Vec<i32>, print it and the sum");
}
Define a struct Fibonacci that implements the Iterator trait and
yields the Fibonacci sequence as u64 values: 0, 1, 1, 2, 3, 5, 8, ... . Pick
type Item = u64 and write next() so each call returns the next number via Some(...)
(this iterator is infinite, so it never returns None). In main, create a Fibonacci,
take the first 10 values with .take(10), collect them into a Vec<u64>, and print the
vector with {:?}. Then print the sum of those 10 values on its own line. This shows that
once you implement next(), all the adaptors (take, collect, sum) work for free.
current and next, starting at 0 and 1.
In next(), save the current value, advance the state (current becomes the old
next, the new next becomes the sum), and return Some(saved). Because the iterator
never ends, you must bound it with .take(10) before collecting. The sum of the first ten
Fibonacci numbers (0 through 34) is 88.// Task 2: implement a custom `Fibonacci` Iterator, take(10), collect, print Vec and sum.
// See tasks/TASKS.md.
fn main() {
todo!("implement Iterator for Fibonacci, then take(10).collect(), print Vec and sum");
}