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

XorT.ensure method #927

Merged
merged 1 commit into from
Mar 16, 2016
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
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))
}
}
}
}