Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add flatten, flatten_right and flatten_left methods #83

Open
CMDJojo opened this issue May 2, 2023 · 2 comments
Open

Add flatten, flatten_right and flatten_left methods #83

CMDJojo opened this issue May 2, 2023 · 2 comments

Comments

@CMDJojo
Copy link

CMDJojo commented May 2, 2023

I think the Either crate is really good, and here are some methods I would love to see:

flatten

I think there should be a flatten method, like for std::Result and std::Option:

impl<L,R> Either<Either<L,R>, Either<L,R>> {
    pub fn flatten(self) -> Either<L,R> {
        match self {
            Left(x) | Right(x) => x
        }
    }
}

As you can see from the implementation, this is the same as into_inner but I think it is good to have this for two reasons:

  • The terminology "flatten" is often used for flattening such nested structures

One alternative may be to let flatten use any Either<T,T> (and thus skip combine).

flatten_right/flatten_left

Two more propsed functions are flatten_right and flatten_left:

impl<L,R> Either<Either<L,R>, R> {
    pub fn flatten_left(self) -> Either<L,R> {
        match self {
            Left(x) => x,
            Right(x) => Right(x)
        }
    }
}

impl<L,R> Either<L, Either<L,R>> {
    pub fn flatten_right(self) -> Either<L,R> {
        match self {
            Right(x) => Right(x),
            Left(x) => x
        }
    }
}

flatten_left is just flatten on std::Result, but it is nice to have corresponding left and right methods to strengthen the intuition that there is nothing special with the left or the right variant, they are both considered equal.

I am fine with doing the implementation itself but I would be glad about comments, naming suggestions and general suggestions! Do you think this would be useful? Maybe it would be confusing with flatten and into_inner doing the same thing so I am fine with dropping that, but flatten_left and flatten_right seems useful imo.

@CMDJojo
Copy link
Author

CMDJojo commented May 2, 2023

Made a PR on flatten_left and flatten_right (but not flatten), see #84

@cuviper
Copy link
Member

cuviper commented Jan 19, 2024

As mentioned on #84:

  • flatten is Either::into_inner
  • flatten_left is Either::left_or_else(Right)
  • flatten_right is Either::right_or_else(left)

If you like, we could add these to the documentation as suggested patterns.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants