Skip to content

Commit

Permalink
"ensure" method for XorT
Browse files Browse the repository at this point in the history
  • Loading branch information
sergeykolbasov committed Mar 10, 2016
1 parent 92a3c5c commit b3cd30a
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 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
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](ifLeft: => AA)(f: B => Boolean)(implicit F: Functor[F]): XorT[F, AA, B] = XorT(F.map(value)(_.ensure(ifLeft)(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 b3cd30a

Please sign in to comment.