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 join a sequence of tuples, each with its own sequence?

I have a sequence of tuples where each tuple contains another sequences.
To better illustrate the problem, please have a look at the below snippet (Rust Playground):

fn main() {
    let data = [
        (vec![1, 2, 3], vec!['a']), 
        (vec![4, 5, 6], vec!['b', 'c'])
    ];
    let res: (Vec<i32>, Vec<char>) = data...?

    // res = (vec![1, 2, 3, 4, 5, 6], vec!['a', 'b', 'c']);

}

I would like to iterate data only once to create two Vecs. Each Vec is a concatenation of all the elements within a corresponding tuple’s member.
res is a commented out expected result.

How this can be achieved in Rust?

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 :

You can use reduce.

let res: (Vec<i32>, Vec<char>) = data
    .into_iter()
    .reduce(|(mut acc1, mut acc2), (mut i1, mut i2)| {
        acc1.append(&mut i1);
        acc2.append(&mut i2);
        (acc1, acc2)
    })
    // An empty sequence will produce `(vec![], vec![])`
    .unwrap_or_default();
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