Skip to content

Commit

Permalink
Implement Traverse for ByColor
Browse files Browse the repository at this point in the history
  • Loading branch information
lenguyenthanh committed Jul 9, 2023
1 parent 59b8abd commit 9906480
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/main/scala/ByColor.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import cats.{ Applicative, Eq, Functor, Monoid }
import cats.syntax.all.*
import scala.annotation.targetName
import alleycats.Zero
import cats.Traverse
import cats.Eval

case class ByColor[A](white: A, black: A):

Expand Down Expand Up @@ -104,6 +106,17 @@ object ByColor:
given Functor[ByColor] with
def map[A, B](fa: ByColor[A])(f: A => B): ByColor[B] = fa.map(f)

given Traverse[ByColor] with

override def foldLeft[A, B](fa: ByColor[A], b: B)(f: (B, A) => B): B =
fa.fold(b)(f)

override def foldRight[A, B](fa: ByColor[A], lb: Eval[B])(f: (A, Eval[B]) => Eval[B]): Eval[B] =
Eval.defer(f(fa.white, Eval.defer(f(fa.black, lb))))

def traverse[G[_]: Applicative, A, B](fa: ByColor[A])(f: A => G[B]): G[ByColor[B]] =
fa.traverse(f)

extension [A](bc: ByColor[IterableOnce[A]]) def flatten: List[A] = bc.all.flatten

extension [A](p: (A, A)) def asByColor: ByColor[A] = ByColor(p._1, p._2)
11 changes: 11 additions & 0 deletions src/test/scala/ByColorLawsTests.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package chess

import cats.laws.discipline.FunctorTests
import munit.DisciplineSuite
import org.scalacheck.*
import Arbitraries.given
import cats.laws.discipline.TraverseTests

class ByColorLawsTest extends DisciplineSuite:
checkAll("ByColor.FunctorLaws", FunctorTests[ByColor].functor[Int, Int, String])
checkAll("ByColor.TraverseLaws", TraverseTests[ByColor].traverse[Int, Int, Int, Int, Option, Option])

0 comments on commit 9906480

Please sign in to comment.