Skip to content

Allow MultiUnzip on Result<tuple, E> with behaviour like collect()? #996

Closed

Description

@shahn

I haven't found a way to make a pattern like this work:

let inputs = vec![(Ok(1), 2, 3), (Ok(4), 5, 6), (Ok(7), 8, 9)];
    
    let (a, b, c): (Vec<_>, Vec<_>, Vec<_>) = inputs.
        into_iter()
        .map(|(x, y, z)| {
            x.map(|x| (x, y, z))
        })
        .multiunzip()?;

It would be great if this could work like collect() to allow short circuiting on an error

Activity

  1. phimuemue commented on Oct 23, 2024

    @phimuemue
    Member

    Hi there, it seems you'd like to collect into three vectors, throwing away all of them if you encounter an Err in any tuple component.

    If so, you probably want try_collect, and your example boiled down to 2-tuples could look as follows:

        let inputs = vec![(Ok::<usize, ()>(1), 2), (Ok(4), 5), (Ok(7), 8)];
        let _: Result<(Vec<_>, Vec<_>), ()> = dbg!(
            inputs.into_iter()
                .map(|(x, y)| x.map(|x| (x, y)))
                .try_collect()
        );
    

    The remaining problem then lies in the fact that FromIterator is only implemented for 2-tuples, but you want 3-tuples. Packing the 3-tuples into nested 2-tuples works around the problem:

        let inputs = vec![(Ok::<usize, ()>(1), 2, 3), (Ok(4), 5, 6), (Ok(7), 8, 9)];
        let (a, (b, c)): (Vec<_>, (Vec<_>, Vec<_>)) = dbg!(
            inputs.into_iter()
                .map(|(x, y, z)| x.map(|x| (x, (y, z))))
                .try_collect()
        ).unwrap();
    

    But I think the adequate way to solve this would be to implement FromIterator (resp. Extend) for 3-tuples. (I'm kinda surprised to see it's only implemented for 2-tuples, because std usually goes up to 12-tuples. Maybe @jswrenn or @scottmcm know the reasons for this limitation.)

  2. phimuemue commented on Oct 23, 2024

    @phimuemue
    Member

    All this raises the question why multiunzip exists in the first place. I guess it's mainly to mirror multizip similar to how unzip mirrors zip.

  3. phimuemue commented on Oct 24, 2024

    @phimuemue
    Member
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions