Skip to content

Commit 2ad6c5a

Browse files
committed
add final polish and fixup names, add comments
1 parent f854578 commit 2ad6c5a

File tree

2 files changed

+8
-7
lines changed

2 files changed

+8
-7
lines changed

exercise-solutions/iterators/src/bin/iterators1.rs

+6-5
Original file line numberDiff line numberDiff line change
@@ -11,20 +11,21 @@ fn main() -> Result<(), Box<dyn Error>> {
1111
// Write your iterator chain here
1212
let sum_of_odd_numbers: i32 = reader.lines()
1313
.map(|l| l.unwrap()) // peel off each line from the BufReader until you're done
14-
.map(|s| s.parse()) // try to parse the line as a number
15-
.filter(|s| s.is_ok()) // keep the lines that actually parsed
14+
.map(|s| s.parse()) // try to parse the line as a number, yields a `Result`
15+
.filter(|s| s.is_ok()) // keep the lines that actually parsed (they're the `Ok` variant)
1616
.map(|l| l.unwrap()) // unwrap the succesful parses, which yield numbers
1717
.filter(|num| num % 2 != 0) // keep the odd numbers
1818
.collect::<Vec<i32>>() // collect the numbers into a vector
1919
.iter() // iterate over the vector
20-
.fold(0, |acc, elem| acc + elem); // fold over the vector and add the elements
20+
.fold(0, |acc, elem| acc + elem); // fold over the vector and add the elements, yields an i32
2121

2222
assert_eq!(sum_of_odd_numbers, 31);
2323

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

exercise-templates/iterators/Cargo.toml

+2-2
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ version = "0.1.0"
44
edition = "2021"
55

66
[[bin]]
7-
name = "iter1"
8-
path = "src/bin/iter1.rs"
7+
name = "iterators1"
8+
path = "src/bin/iterators1.rs"
99

1010
[dependencies]

0 commit comments

Comments
 (0)