Skip to content

Commit

Permalink
Merge pull request #927 from ImLiar/xort-ensure
Browse files Browse the repository at this point in the history
XorT.ensure method
  • Loading branch information
stew committed Mar 16, 2016
2 parents aa348c0 + c4b4134 commit 8edf0a3
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 2 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,4 @@ TAGS
.sbtrc
*.sublime-project
*.sublime-workspace
tests.iml
4 changes: 2 additions & 2 deletions core/src/main/scala/cats/data/Xor.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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)

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

0 comments on commit 8edf0a3

Please sign in to comment.