From c4b4134246ffa500070c5098ad38f2a3f2fe4867 Mon Sep 17 00:00:00 2001 From: ImLiar Date: Fri, 11 Mar 2016 00:11:55 +0300 Subject: [PATCH] "ensure" method for XorT --- .gitignore | 1 + core/src/main/scala/cats/data/Xor.scala | 4 ++-- core/src/main/scala/cats/data/XorT.scala | 2 ++ .../src/test/scala/cats/tests/XorTTests.scala | 24 +++++++++++++++++++ 4 files changed, 29 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index 4c19d3d8e4..4581b4d5be 100644 --- a/.gitignore +++ b/.gitignore @@ -16,3 +16,4 @@ TAGS .sbtrc *.sublime-project *.sublime-workspace +tests.iml diff --git a/core/src/main/scala/cats/data/Xor.scala b/core/src/main/scala/cats/data/Xor.scala index b086575a13..ef778bc37a 100644 --- a/core/src/main/scala/cats/data/Xor.scala +++ b/core/src/main/scala/cats/data/Xor.scala @@ -59,8 +59,8 @@ sealed abstract class Xor[+A, +B] extends Product with Serializable { def exists(f: B => Boolean): Boolean = fold(_ => false, f) - def ensure[AA >: A](ifLeft: => AA)(f: B => Boolean): AA Xor B = - fold(_ => this, b => if (f(b)) this else Xor.Left(ifLeft)) + def ensure[AA >: A](onFailure: => AA)(f: B => Boolean): AA Xor B = + fold(_ => this, b => if (f(b)) this else Xor.Left(onFailure)) def toIor: A Ior B = fold(Ior.left, Ior.right) diff --git a/core/src/main/scala/cats/data/XorT.scala b/core/src/main/scala/cats/data/XorT.scala index d7ff05bf80..71d4a97c28 100644 --- a/core/src/main/scala/cats/data/XorT.scala +++ b/core/src/main/scala/cats/data/XorT.scala @@ -51,6 +51,8 @@ final case class XorT[F[_], A, B](value: F[A Xor B]) { def exists(f: B => Boolean)(implicit F: Functor[F]): F[Boolean] = F.map(value)(_.exists(f)) + def ensure[AA >: A](onFailure: => AA)(f: B => Boolean)(implicit F: Functor[F]): XorT[F, AA, B] = XorT(F.map(value)(_.ensure(onFailure)(f))) + def toEither(implicit F: Functor[F]): F[Either[A, B]] = F.map(value)(_.toEither) def toOption(implicit F: Functor[F]): OptionT[F, B] = OptionT(F.map(value)(_.toOption)) diff --git a/tests/src/test/scala/cats/tests/XorTTests.scala b/tests/src/test/scala/cats/tests/XorTTests.scala index f75b14a713..7ea4e9b343 100644 --- a/tests/src/test/scala/cats/tests/XorTTests.scala +++ b/tests/src/test/scala/cats/tests/XorTTests.scala @@ -251,4 +251,28 @@ class XorTTests extends CatsSuite { x.toEither.map(_.right.toOption) should === (x.toOption.value) } } + + test("ensure on left is identity") { + forAll { (x: XorT[Id, String, Int], s: String, p: Int => Boolean) => + if (x.isLeft) { + x.ensure(s)(p) should === (x) + } + } + } + + test("ensure on right is identity if predicate satisfied") { + forAll { (x: XorT[Id, String, Int], s: String, p: Int => Boolean) => + if (x.isRight && p(x getOrElse 0)) { + x.ensure(s)(p) should === (x) + } + } + } + + test("ensure should fail if predicate not satisfied") { + forAll { (x: XorT[Id, String, Int], s: String, p: Int => Boolean) => + if (x.isRight && !p(x getOrElse 0)) { + x.ensure(s)(p) should === (XorT.left[Id, String, Int](s)) + } + } + } }