Skip to content

Commit

Permalink
add final polish and fixup names, add comments
Browse files Browse the repository at this point in the history
  • Loading branch information
miguelraz committed Jan 15, 2025
1 parent f854578 commit 2ad6c5a
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 7 deletions.
11 changes: 6 additions & 5 deletions exercise-solutions/iterators/src/bin/iterators1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,21 @@ fn main() -> Result<(), Box<dyn Error>> {
// Write your iterator chain here
let sum_of_odd_numbers: i32 = reader.lines()
.map(|l| l.unwrap()) // peel off each line from the BufReader until you're done
.map(|s| s.parse()) // try to parse the line as a number
.filter(|s| s.is_ok()) // keep the lines that actually parsed
.map(|s| s.parse()) // try to parse the line as a number, yields a `Result`
.filter(|s| s.is_ok()) // keep the lines that actually parsed (they're the `Ok` variant)
.map(|l| l.unwrap()) // unwrap the succesful parses, which yield numbers
.filter(|num| num % 2 != 0) // keep the odd numbers
.collect::<Vec<i32>>() // collect the numbers into a vector
.iter() // iterate over the vector
.fold(0, |acc, elem| acc + elem); // fold over the vector and add the elements
.fold(0, |acc, elem| acc + elem); // fold over the vector and add the elements, yields an i32

assert_eq!(sum_of_odd_numbers, 31);

// Idiomatic solution
let second_reader = BufReader::new(File::open("../exercise-solutions/iterators/numbers.txt")?);
let nicer_sum: i32 = second_reader.lines()
.map(|l| l.unwrap())
.filter_map(|s| s.parse().ok())
.map(|l| l.unwrap())
.filter_map(|s| s.parse().ok()) // map a .parse() and filter for the succesful parses
.filter(|num| num % 2 != 0)
.sum::<i32>();

Expand Down
4 changes: 2 additions & 2 deletions exercise-templates/iterators/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2021"

[[bin]]
name = "iter1"
path = "src/bin/iter1.rs"
name = "iterators1"
path = "src/bin/iterators1.rs"

[dependencies]

0 comments on commit 2ad6c5a

Please sign in to comment.