Skip to content

Add flatten, flatten_right and flatten_left methods #83

@CMDJojo

Description

@CMDJojo

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.

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