@@ -11,20 +11,21 @@ fn main() -> Result<(), Box<dyn Error>> {
11
11
// Write your iterator chain here
12
12
let sum_of_odd_numbers: i32 = reader. lines ( )
13
13
. 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)
16
16
. map ( |l| l. unwrap ( ) ) // unwrap the succesful parses, which yield numbers
17
17
. filter ( |num| num % 2 != 0 ) // keep the odd numbers
18
18
. collect :: < Vec < i32 > > ( ) // collect the numbers into a vector
19
19
. 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
21
21
22
22
assert_eq ! ( sum_of_odd_numbers, 31 ) ;
23
23
24
+ // Idiomatic solution
24
25
let second_reader = BufReader :: new ( File :: open ( "../exercise-solutions/iterators/numbers.txt" ) ?) ;
25
26
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
28
29
. filter ( |num| num % 2 != 0 )
29
30
. sum :: < i32 > ( ) ;
30
31
0 commit comments