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 authored and karpin_r committed Aug 28, 2017
1 parent 0519906 commit cd38406
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
12 changes: 12 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,18 @@ 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] =
EitherT(F.flatMap(value) {
case Left(a) => F.map(f(a)) { d => Left(d) }
case r@Right(_) => F.pure(r.leftCast)
})

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 cd38406

Please sign in to comment.