Skip to content

Commit

Permalink
Add leftFlatMap to Either (#2149)
Browse files Browse the repository at this point in the history
* Add leftFlatMap to Either syntax

* Add tests for Either leftFlatMap
  • Loading branch information
rohanshah authored and johnynek committed Jan 12, 2018
1 parent 65d5933 commit 5f30a73
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
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)
}
}

}

0 comments on commit 5f30a73

Please sign in to comment.