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 leftFlatMap to Either #2149

Merged
merged 2 commits into from
Jan 12, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions core/src/main/scala/cats/syntax/either.scala
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,11 @@ final class EitherOps[A, B](val eab: Either[A, B]) extends AnyVal {
case Right(b) => f(b)
}

def leftFlatMap[C, BB >: B](f: A => Either[C, BB]): Either[C, BB] = eab match {
case Left(a) => f(a)
case r @ Right(_) => EitherUtil.leftCast(r)
}

def compare[AA >: A, BB >: B](that: Either[AA, BB])(implicit AA: Order[AA], BB: Order[BB]): Int = eab match {
case Left(a1) =>
that match {
Expand Down
12 changes: 12 additions & 0 deletions tests/src/test/scala/cats/tests/EitherSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -282,4 +282,16 @@ class EitherSuite extends CatsSuite {
}
}

test("leftFlatMap consistent with leftMap") {
forAll { (either: Either[String, Int], f: String => String) =>
either.leftFlatMap(v => Left(f(v))) should === (either.leftMap(f))
}
}

test("leftFlatMap consistent with swap and then flatMap") {
forAll { (either: Either[String, Int], f: String => Either[String, Int]) =>
either.leftFlatMap(f) should === (either.swap.flatMap(a => f(a).swap).swap)
}
}

}