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 Validated.swap #731

Merged
merged 1 commit into from
Dec 11, 2015
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
4 changes: 4 additions & 0 deletions core/src/main/scala/cats/data/Validated.scala
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,10 @@ sealed abstract class Validated[+E, +A] extends Product with Serializable {
case _ => that
}

def swap: Validated[A, E] = this match {
case Valid(a) => Invalid(a)
case Invalid(e) => Valid(e)
}
}

object Validated extends ValidatedInstances with ValidatedFunctions{
Expand Down
13 changes: 13 additions & 0 deletions tests/src/test/scala/cats/tests/CoproductTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,17 @@ class CoproductTests extends CatsSuite {
}
}

test("swap negates isLeft/isRight") {
forAll { (x: Coproduct[Option, Option, Int]) =>
x.isLeft should !== (x.swap.isLeft)
x.isRight should !== (x.swap.isRight)
}
}

test("isLeft consistent with isRight") {
forAll { (x: Coproduct[Option, Option, Int]) =>
x.isLeft should !== (x.isRight)
}
}

}
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 @@ -154,4 +154,23 @@ class ValidatedTests extends CatsSuite {
}
}

test("isInvalid consistent with isValid") {
forAll { (x: Validated[String, Int]) =>
x.isInvalid should !== (x.isValid)
}
}

test("double swap is identity") {
forAll { (x: Validated[String, Int]) =>
x.swap.swap should ===(x)
}
}

test("swap negates isInvalid/isValid") {
forAll { (x: Validated[String, Int]) =>
x.isInvalid should !== (x.swap.isInvalid)
x.isValid should !== (x.swap.isValid)
}
}

}
13 changes: 13 additions & 0 deletions tests/src/test/scala/cats/tests/XorTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,19 @@ class XorTests extends CatsSuite {
}
}

test("swap negates isLeft/isRight") {
forAll { (x: Int Xor String) =>
x.isLeft should !== (x.swap.isLeft)
x.isRight should !== (x.swap.isRight)
}
}

test("isLeft consistent with isRight") {
forAll { (x: Int Xor String) =>
x.isLeft should !== (x.isRight)
}
}

test("foreach is noop for left") {
forAll { (x: Int Xor String) =>
var count = 0
Expand Down