Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add XorT.orElse #714

Merged
merged 1 commit into from
Dec 6, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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