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

How to use map that has more than one output?

So far I use the map function as a 1-1 relationship, such as the following example:

let vector = [1, 2, 3];
let result: Vec<_> = vector.iter().map(|x| x * 2).map(|x| x + 1).collect();
println!("After mapping: {:?}", result);
// After mapping: [3, 5, 7]

In this example there are 2 map function and both function are having a 1-1 relationship. I would like to know how could I change the code such that the first map function could provide output multiple (e.g. 2) output to the second map function?

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 :

To achieve a 1-to-many relationship in the context of your example, you can use the flat_map function. Here’s how you can modify your code:

let vector = [1, 2, 3];
let result: Vec<_> = vector
    .iter()
    .flat_map(|x| vec![x * 2, x * 3]) // Modify this line to produce multiple outputs
    .map(|x| x + 1)
    .collect();
println!("After mapping: {:?}", result);

In this example, flat_map takes a closure that produces an iterator, and the results are flattened into a single iterator. Here, I used vec![x * 2, x * 3] to produce two outputs for each element in the original vector. The subsequent map then operates on each of these values, resulting in the final mapped vector [3, 4, 5, 6, 7, 10].

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