Skip to content

Commit

Permalink
Add XorT.orElse
Browse files Browse the repository at this point in the history
  • Loading branch information
rossabaker committed Dec 5, 2015
1 parent 7891cd8 commit 5471bd4
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
9 changes: 9 additions & 0 deletions core/src/main/scala/cats/data/XorT.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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)))

Expand Down
15 changes: 15 additions & 0 deletions tests/src/test/scala/cats/tests/XorTTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down

0 comments on commit 5471bd4

Please sign in to comment.