Skip to content

Commit

Permalink
Implement EitherT#leftFlatMap and EitherT#leftSemiflatMap
Browse files Browse the repository at this point in the history
  • Loading branch information
vendethiel committed Aug 6, 2017
1 parent 0519906 commit 8de4070
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
9 changes: 9 additions & 0 deletions core/src/main/scala/cats/data/EitherT.scala
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,15 @@ final case class EitherT[F[_], A, B](value: F[Either[A, B]]) {

def leftMap[C](f: A => C)(implicit F: Functor[F]): EitherT[F, C, B] = bimap(f, identity)

def leftFlatMap[BB >: B, D](f: A => EitherT[F, D, BB])(implicit F: Monad[F]): EitherT[F, D, BB] =
EitherT(F.flatMap(value) {
case Left(a) => f(a).value
case r@Right(_) => F.pure(r.leftCast)
})

def leftSemiflatMap[D](f: A => F[D])(implicit F: Monad[F]): EitherT[F, D, B] =
leftFlatMap(a => EitherT.left(f(a)))

def compare(that: EitherT[F, A, B])(implicit o: Order[F[Either[A, B]]]): Int =
o.compare(value, that.value)

Expand Down
12 changes: 12 additions & 0 deletions tests/src/test/scala/cats/tests/EitherTTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -434,4 +434,16 @@ class EitherTTests extends CatsSuite {
} yield s1 ++ s2
}

test("leftFlatMap") {
forAll { (eithert: EitherT[List, String, Int], f: String => String) =>
eithert.leftFlatMap(v => EitherT.left[Int](List(f(v)))) should ===(eithert.leftMap(f))
}
}

test("leftSemiflatMap") {
forAll { (eithert: EitherT[List, String, Int], f: String => String) =>
eithert.leftSemiflatMap(v => List(f(v))) should ===(eithert.leftMap(f))
}
}

}

0 comments on commit 8de4070

Please sign in to comment.