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 SemigroupK instance for Validated + tests #998

Merged
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
12 changes: 11 additions & 1 deletion core/src/main/scala/cats/data/Validated.scala
Original file line number Diff line number Diff line change
Expand Up @@ -210,9 +210,19 @@ object Validated extends ValidatedInstances with ValidatedFunctions{
final case class Invalid[+E](e: E) extends Validated[E, Nothing]
}


private[data] sealed abstract class ValidatedInstances extends ValidatedInstances1 {

implicit def validatedSemigroupK[A](implicit A: Semigroup[A]): SemigroupK[Validated[A,?]] =
new SemigroupK[Validated[A,?]] {
def combineK[B](x: Validated[A,B], y: Validated[A,B]): Validated[A,B] = x match {
case v @ Valid(_) => v
case Invalid(ix) => y match {
case Invalid(iy) => Invalid(A.combine(ix,iy))
case v @ Valid(_) => v
}
}
}

implicit def validatedMonoid[A, B](implicit A: Semigroup[A], B: Monoid[B]): Monoid[Validated[A, B]] = new Monoid[Validated[A, B]] {
def empty: Validated[A, B] = Valid(B.empty)
def combine(x: Validated[A, B], y: Validated[A, B]): Validated[A, B] = x combine y
Expand Down
7 changes: 7 additions & 0 deletions tests/src/test/scala/cats/tests/ValidatedTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import cats.data.{NonEmptyList, Validated, ValidatedNel, Xor, XorT}
import cats.data.Validated.{Valid, Invalid}
import cats.laws.discipline.{BifunctorTests, TraverseTests, ApplicativeErrorTests, SerializableTests, CartesianTests}
import org.scalacheck.Arbitrary._
import cats.laws.discipline.{SemigroupKTests}
import cats.laws.discipline.arbitrary._
import cats.laws.discipline.eq.tuple3Eq
import algebra.laws.{OrderLaws, GroupLaws}
Expand Down Expand Up @@ -33,6 +34,12 @@ class ValidatedTests extends CatsSuite {

checkAll("Validated[String, NonEmptyList[Int]]", GroupLaws[Validated[String, NonEmptyList[Int]]].semigroup)

{
implicit val L = ListWrapper.semigroup[String]
checkAll("Validated[ListWrapper[String], ?]", SemigroupKTests[Validated[ListWrapper[String], ?]].semigroupK[Int])
checkAll("SemigroupK[Validated[ListWrapper[String], ?]]", SerializableTests.serializable(SemigroupK[Validated[ListWrapper[String], ?]]))
}

{
implicit val S = ListWrapper.partialOrder[String]
implicit val I = ListWrapper.partialOrder[Int]
Expand Down