fold algorithm that yields each partial result

Bar*_*rry 4 rust

The rust standard library has a fold() which collapses an iterator into a single result:

let a = [1, 2, 3];

// the sum of all of the elements of the array
let sum = a.iter().fold(0, |acc, x| acc + x);

assert_eq!(sum, 6);
Run Code Online (Sandbox Code Playgroud)

Does the standard library have an equivalent version that yields each element? That is, something like:

let partial_sums = a.iter()
   .what_goes_here(0, |acc, x| acc + x)
   .collect::<Vec<_>>();
assert_eq!(partial_sums, vec![1, 3, 6]);
Run Code Online (Sandbox Code Playgroud)

Effectively, iter.fold(init, f) is semantically equivalent to

iter
    .what_goes_here(init, f)
    .last()
    .unwrap_or(init)
Run Code Online (Sandbox Code Playgroud)

For anyone in the same boat as me, I'm looking for the Rust equivalent of the C++ algorithm partial_sum.

edw*_*rdw 6

你想要Iterator::scan

fn main() {
    let v = vec![1, 2, 3];
    let res = v
        .iter()
        .scan(0, |acc, &x| {
            *acc += x;
            Some(*acc)
        })
        .collect::<Vec<_>>();
    assert_eq!(res, vec![1, 3, 6]);
}
Run Code Online (Sandbox Code Playgroud)