rust - How do I sum a vector using fold? -
this rust tutorial explains fold()
mechanism well, , example code:
let sum = (1..4).fold(0, |sum, x| sum + x);
works expected.
i'd run on vector, based on example, first wrote this:
let sum: u32 = vec![1,2,3,4,5,6].iter().fold(0, |sum, val| sum += val);
which throwed error:
error: binary assignment operation `+=` cannot applied types `_` , `&u32` [e0368] let sum = ratings.values().fold(0, |sum, val| sum += val); ^~~~~~~~~~
i guessed might reference-related error reason, changed fold(0, |sum, &val| sum += val)
, resulted with
error: mismatched types: expected `u32`, found `()`
hm, maybe something's wrong closure? using {sum += x; sum }
, got
binary assignment operation `+=` cannot applied types `_` , `&u32`
again.
after further trials , errors, adding mut
sum
worked:
let sum = vec![1,2,3,4,5,6].iter().fold(0, |mut sum, &x| {sum += x; sum});
could explain reason why fold()
vectors differs tutorial? or, there better way handle this?
for reference, i'm using rust beta, 2015-04-02.
you've figured out +=
problem, i'd provide more exposition.
in case, arguments provided fold
closure _
, &u32
. first type not-yet-specified integer. if change fold call fold(0u32, |sum, val| sum += val)
, you'll different message:
let sum: u32 = vec![1,2,3,4,5,6].iter().fold(0u32, |sum, val| sum += val);
error[e0308]: mismatched types | 2 | let sum: u32 = vec![1,2,3,4,5,6].iter().fold(0u32, |sum, val| sum += val); | ^^^ expected u32, found &{integer} | = note: expected type `u32` = note: found type `&{integer}`
the result value of binary assignment operation +=
()
, unit type. explains error message when changed fold(0, |sum, &val| sum += val)
:
let mut = 1; let what_am_i = += 1; println!("{:?}", what_am_i); // => ()
if change fold(0, |sum, &val| {sum += val ; sum})
, understandable error immutable variables:
let sum: u32 = vec![1,2,3,4,5,6].iter().fold(0, |sum, &val| {sum += val; sum});
error[e0384]: re-assignment of immutable variable `sum` --> src/main.rs:2:66 | 2 | let sum: u32 = vec![1,2,3,4,5,6].iter().fold(0, |sum, &val| {sum += val; sum}); | --- ^^^^^^^^^^ re-assignment of immutable variable | | | first assignment `sum`
from here, could mark sum
mutable, correct solution fold sum + val
, discovered.
in newer versions of rust, can sum
iterator directly, skipping fold
:
let sum: u32 = vec![1,2,3,4,5,6].iter().sum();