If I have an list of numbers [1, 2, 3, 4, 5] and I wanted to generate a cumulative sum list, in Haskell I would do the following:
> let xs = [1, 2, 3, 4, 5]
> scanl (+) 0 xs
[0,1,3,6,10,15]
Trying to get this same behaviour seems unnecessarily troublesome in Rust.
let xs = [1, 2, 3, 4, 5];
let vs = vec![0]
.into_iter()
.chain(xs.iter().scan(0, |acc, x| {
*acc += x;
Some(*acc)
}))
.collect::<Vec<_>>();
The awkward scan behaviour of having to mutate the accumulator can be explained by a lack of GC. But, scan also does not include the initial accumulator value, necessitating the need to manually prepend a 0 at the front. This itself was troublesome, as I needed to prepend it with chain and [0].iter() didn't work, nor did [0].into_iter() and vec![0].iter(). It needed vec![0].into_iter().
I feel like I must be doing something wrong here. But, what? Is there a better way to generate a cumulative sum? Is it back to a for loop?