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 or combinator to Validated #1448

Merged
merged 2 commits into from
Nov 15, 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
14 changes: 14 additions & 0 deletions core/src/main/scala/cats/data/Validated.scala
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,27 @@ sealed abstract class Validated[+E, +A] extends Product with Serializable {

/**
* Return this if it is Valid, or else fall back to the given default.
* The functionality is similar to that of [[findValid]] except for failure accumulation,
* where here only the error on the right is preserved and the error on the left is ignored.
*/
def orElse[EE, AA >: A](default: => Validated[EE, AA]): Validated[EE, AA] =
this match {
case v @ Valid(_) => v
case Invalid(_) => default
}

/**
* If `this` is valid return `this`, otherwise if `that` is valid return `that`, otherwise combine the failures.
* This is similar to [[orElse]] except that here failures are accumulated.
*/
def findValid[EE >: E, AA >: A](that: => Validated[EE, AA])(implicit EE: Semigroup[EE]): Validated[EE, AA] = this match {
case v @ Valid(_) => v
case Invalid(e) => that match {
case v @ Valid(_) => v
case Invalid(ee) => Invalid(EE.combine(e, ee))
}
}

/**
* Converts the value to an Either[E, A]
*/
Expand Down
19 changes: 19 additions & 0 deletions tests/src/test/scala/cats/tests/ValidatedTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,25 @@ class ValidatedTests extends CatsSuite {
}
}

test("findValid accumulates failures") {
forAll { (v: Validated[String, Int], u: Validated[String, Int]) =>
v findValid u shouldEqual { (v, u) match {
case (vv @ Valid(_), _) => vv
case (_, uu @ Valid(_)) => uu
case (Invalid(s1), Invalid(s2)) => Invalid(s1 ++ s2)
}}
}
}

test("orElse ignores left failure") {
forAll { (v: Validated[String, Int], u: Validated[String, Int]) =>
v orElse u shouldEqual { (v, u) match {
case (vv @ Valid(_), _) => vv
case (_, uu) => uu
}}
}
}

test("valueOr consistent with swap then map then merge") {
forAll { (v: Validated[String, Int], f: String => Int) =>
v.valueOr(f) should === (v.swap.map(f).merge)
Expand Down