Can I do this with an iterator?

Viewed 94

Hi I wrote a function that maps a vector to the interval [0,1]:

fn vec2interval(v: &Vec<f32>) -> Vec<f32> {
    let total: f32 = v.iter().sum();
    let mut interval: Vec<f32> = vec![0f32; v.len()];
    interval[0] = v[0] / total;
    for i in 1..v.len() {
        interval[i] = interval[i-1] + v[i] / total;
    }
    return interval;
}

Is there any way to do the same with iterator? I wrote the following but it's slower and needs a for loop:

fn vec2interval(v: &Vec<f32>) -> Vec<f32> {
    let total: f32 = v.iter().sum();
    let mut interval: Vec<f32> = v
        .iter()
        .map(|x| x / total)
        .collect::<Vec<f32>>();
    for i in 1..v.len() {
        interval[i] = interval[i-1] + interval[i];
    }
    return interval;
}
1 Answers

scan can do all of the job:

fn vec2interval(v: &Vec<f32>) -> Vec<f32> {
    let total: f32 = v.iter().sum();

    v.iter()
        .scan(0.0, |acc, x| {
            *acc += x / total;
            Some(*acc)
        })
        .collect()
}

Also, slice (&[u8]) better be used instead of Vec<_> as a parameter.

Related