Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rust: apply the function to each element of vector

Given the following function:

fn some_function<K, F: Fn(K) -> K>(f: F, vs: Vec<K>) -> Vec<K> {
    let mut index = 0;
    let new_vec = vs.iter().map(|x| {
        index += 1;
        for _ in 1 .. index {
            x = f(x); // <- error here: mismatched types expected reference `&K` found type parameter `K`
        }
        *x
    }).collect();
    new_vec
}

How can i make it work ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This example doesn’t work because .iter() will not produce an iterator of owned variables, but references to elements of vs. You could patch your code by turning it into into_iter():

fn some_function<K>(f: impl Fn(K) -> K, vs: Vec<K>) -> Vec<K> {
    let mut index = 0;
    vs.into_iter()
    .map(|mut x| {
        index += 1;
        for _ in 1..index { x = f(x); }
        x
    })
    .collect()
}

But you don’t need to keep track of index:

fn some_function<K>(f: impl Fn(K) -> K, vs: Vec<K>) -> Vec<K> {
    vs
    .into_iter()
    .enumerate()
    .map(|(i, mut x)| {
        for _ in 0..i { x = f(x); }
        x
    })
   .collect()
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading