Implement `bimap` which combines `left_map` and `right_map`
Closed this issue · 2 comments
bimap
is a function from the Bifunctor typeclass commonly seen implemented for the Either type.
This library already has map_left
and map_right
, so the implementation would simply be a combination of the two. Would the maintainers be interested in adding this combinator?
Example as an extension:
trait EitherExt {
type L;
type R;
fn bimap<M, S, F: Fn(Self::L) -> M, G: Fn(Self::R) -> S>(
self,
f: F,
g: G,
) -> Either<M, S>;
}
impl<L, R> EitherExt for Either<L, R> {
type L = L;
type R = R;
fn bimap<M, S, F: Fn(Self::L) -> M, G: Fn(Self::R) -> S>(
self,
f: F,
g: G,
) -> Either<M, S> {
self.map_left(f).map_right(g)
}
}
I'd call it map_either
, if only because my first thought at "bimap" was the data structure.
The idea has limitations compared to .map_left(f).map_right(g)
, because you're forcing those two closures to coexist -- e.g. they can't use the same &mut
capture. This is why either has a corresponding either_with. I suppose we could do the same here.
I would implement it with a plain match
though.
Thanks @cuviper for your response. Though bimap
is canonical in FP, I don't mind calling it map_either
or map_both
to keep in the spirit of this library.
I can add a map_either_with
variant so both closures can capture the same context. PR coming.