From 793b3e7f60a11007bdffa9d9ff40774c0e0cb141 Mon Sep 17 00:00:00 2001 From: Erik LaBianca Date: Mon, 30 Nov 2015 19:07:59 -0500 Subject: [PATCH] Add getOrElseF method to XorT --- core/src/main/scala/cats/data/XorT.scala | 7 +++++++ tests/src/test/scala/cats/tests/XorTTests.scala | 6 ++++++ 2 files changed, 13 insertions(+) diff --git a/core/src/main/scala/cats/data/XorT.scala b/core/src/main/scala/cats/data/XorT.scala index 5bc5669bbe9..05321816531 100644 --- a/core/src/main/scala/cats/data/XorT.scala +++ b/core/src/main/scala/cats/data/XorT.scala @@ -22,6 +22,13 @@ final case class XorT[F[_], A, B](value: F[A Xor B]) { def getOrElse[BB >: B](default: => BB)(implicit F: Functor[F]): F[BB] = F.map(value)(_.getOrElse(default)) + def getOrElseF[BB >: B](default: => F[BB])(implicit F: Monad[F]): F[BB] = { + F.flatMap(value) { + case Xor.Left(a) => default + case Xor.Right(a) => F.pure(a) + } + } + def recover(pf: PartialFunction[A, B])(implicit F: Functor[F]): XorT[F, A, B] = XorT(F.map(value)(_.recover(pf))) diff --git a/tests/src/test/scala/cats/tests/XorTTests.scala b/tests/src/test/scala/cats/tests/XorTTests.scala index de5287af4d8..323888f8330 100644 --- a/tests/src/test/scala/cats/tests/XorTTests.scala +++ b/tests/src/test/scala/cats/tests/XorTTests.scala @@ -157,6 +157,12 @@ class XorTTests extends CatsSuite { } } + test("getOrElseF with Id consistent with Xor getOrElse") { + forAll { (xort: XorT[Id, String, Int], i: Int) => + xort.getOrElseF(i) should === (xort.value.getOrElse(i)) + } + } + test("forall with Id consistent with Xor forall") { forAll { (xort: XorT[Id, String, Int], f: Int => Boolean) => xort.forall(f) should === (xort.value.forall(f))