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

Implement bimap which combines left_map and right_map #81

Closed
nasadorian opened this issue Apr 19, 2023 · 2 comments · Fixed by #82
Closed

Implement bimap which combines left_map and right_map #81

nasadorian opened this issue Apr 19, 2023 · 2 comments · Fixed by #82

Comments

@nasadorian
Copy link
Contributor

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)
  }
}
@cuviper
Copy link
Member

cuviper commented Apr 20, 2023

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.

@nasadorian
Copy link
Contributor Author

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.

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