0

how to write a clean suffix sum function using cascade in rust?

This doesnt work, does the two rev() somehow get canceled out?

    fn suffix_sum(vec: &Vec<i32>) -> Vec<i32> {
        let mut sum = 0;
        return vec.clone().into_iter().rev().map(|val| {
            sum += val;
            return sum;
        }).rev().collect::<Vec<i32>>();
    }

This works, but calling iter() and collect() twice seems stupid

    fn suffix_sum(vec: &Vec<i32>) -> Vec<i32> {
        let mut sum = 0;
        return vec.clone().into_iter().rev().map(|val| {
            sum += val;
            return sum;
        }).collect::<Vec<i32>>().into_iter().rev().collect::<Vec<i32>>();
    }
  • nit: `.iter().copied()` instead of `.clone().into_iter()` avoids one allocation of a `Vec`. And you should [take `&[i32]` instead of `&Vec`](https://stackoverflow.com/questions/40006219/why-is-it-discouraged-to-accept-a-reference-string-vec-or-box-as-a-function) – cafce25 Feb 22 '23 at 15:53

1 Answers1

0

Perhaps this one:

fn suffix_sum(vec: &[i32]) -> Vec<i32> {
    let mut res : Vec<i32> = vec.iter().rev().scan(0, |state, &x| {
        *state += x;
        Some(*state)
    }).collect();
    res.reverse();
    res
}

Playground: here

Arnab De
  • 402
  • 4
  • 12