Prefix sum of Vec

Hey,

I need to calculate a simple prefix sum over a vector in Rust. Googling didn’t yield any useful results. Is there a function in the standard library for that? Or is it possible to use iterators in a clever way?

fn main() {
    let a = vec![1, 2, 3];
    let cumsum = a.iter().scan(0, |sum, i| {*sum += i; Some(*sum)}).collect::<Vec<_>>();
    println!("Cumsum is: {:?}", cumsum);
}

Outputs:

Cumsum is: [1, 3, 6]
3 Likes

Thank you very much, this is really cool!
Are there any plans of including functionality like this as standard library functions, like C++'s std::numeric::partial_sum?

The ergonomy of Rust scan is not stellar, but it’s meant to be used in Rust as replacement to C++ partial_sum.

An implementation with SIMD instructions could be sweet.

1 Like