either icon indicating copy to clipboard operation
either copied to clipboard

Add `flatten`, `flatten_right` and `flatten_left` methods

Open CMDJojo opened this issue 2 years ago • 2 comments

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 avatar May 02 '23 01:05 CMDJojo

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

CMDJojo avatar May 02 '23 01:05 CMDJojo

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.

cuviper avatar Jan 19 '24 00:01 cuviper