Skip to content

Commit

Permalink
Add valueOrF to EitherT (#2192)
Browse files Browse the repository at this point in the history
  • Loading branch information
denisrosca authored and kailuowang committed Mar 14, 2018
1 parent 5b85396 commit f644982
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
7 changes: 7 additions & 0 deletions core/src/main/scala/cats/data/EitherT.scala
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,13 @@ final case class EitherT[F[_], A, B](value: F[Either[A, B]]) {

def valueOr[BB >: B](f: A => BB)(implicit F: Functor[F]): F[BB] = fold(f, identity)

def valueOrF[BB >: B](f: A => F[BB])(implicit F: Monad[F]): F[BB] = {
F.flatMap(value){
case Left(a) => f(a)
case Right(b) => F.pure(b)
}
}

def forall(f: B => Boolean)(implicit F: Functor[F]): F[Boolean] = F.map(value)(_.forall(f))

def exists(f: B => Boolean)(implicit F: Functor[F]): F[Boolean] = F.map(value)(_.exists(f))
Expand Down
6 changes: 6 additions & 0 deletions tests/src/test/scala/cats/tests/EitherTSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,12 @@ class EitherTSuite extends CatsSuite {
}
}

test("valueOrF with Id consistent with Either valueOr") {
forAll{ (eithert: EitherT[Id, String, Int], f: String => Int) =>
eithert.valueOrF(f) should === (eithert.value.valueOr(f))
}
}

test("getOrElse with Id consistent with Either getOrElse") {
forAll { (eithert: EitherT[Id, String, Int], i: Int) =>
eithert.getOrElse(i) should === (eithert.value.getOrElse(i))
Expand Down

0 comments on commit f644982

Please sign in to comment.