From 5471bd4544d8065185e850ed07dc8e254a3a68b6 Mon Sep 17 00:00:00 2001 From: "Ross A. Baker" Date: Fri, 4 Dec 2015 21:59:01 -0500 Subject: [PATCH] Add XorT.orElse --- core/src/main/scala/cats/data/XorT.scala | 9 +++++++++ tests/src/test/scala/cats/tests/XorTTests.scala | 15 +++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/core/src/main/scala/cats/data/XorT.scala b/core/src/main/scala/cats/data/XorT.scala index 7736113826..6bc5c4a23c 100644 --- a/core/src/main/scala/cats/data/XorT.scala +++ b/core/src/main/scala/cats/data/XorT.scala @@ -29,6 +29,15 @@ final case class XorT[F[_], A, B](value: F[A Xor B]) { } } + def orElse[AA >: A, BB >: B](default: => XorT[F, AA, BB])(implicit F: Monad[F]): XorT[F, AA, BB] = { + XorT(F.flatMap(value) { xor => + xor match { + case Xor.Left(_) => default.value + case _ => F.pure(xor) + } + }) + } + 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 323888f833..067b9da785 100644 --- a/tests/src/test/scala/cats/tests/XorTTests.scala +++ b/tests/src/test/scala/cats/tests/XorTTests.scala @@ -163,6 +163,21 @@ class XorTTests extends CatsSuite { } } + test("orElse with Id consistent with Xor orElse") { + forAll { (xort: XorT[Id, String, Int], fallback: XorT[Id, String, Int]) => + xort.orElse(fallback).value should === (xort.value.orElse(fallback.value)) + } + } + + test("orElse evaluates effect only once") { + forAll { (xor: String Xor Int, fallback: XorT[Eval, String, Int]) => + var evals = 0 + val xort = (XorT(Eval.always { evals += 1; xor }) orElse fallback) + xort.value.value + evals should === (1) + } + } + 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))