Skip to content

Commit

Permalink
Add Zero, Monoid, Functor for ByColor
Browse files Browse the repository at this point in the history
  • Loading branch information
lenguyenthanh committed Jun 29, 2023
1 parent 90dfaf1 commit 6d3a54e
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/main/scala/ByColor.scala
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package chess

import cats.{ Applicative, Eq }
import cats.{ Applicative, Eq, Functor, Monoid }
import cats.syntax.all.*
import scala.annotation.targetName
import alleycats.Zero

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

Expand Down Expand Up @@ -85,6 +86,17 @@ object ByColor:
def eqv(x: ByColor[A], y: ByColor[A]) =
x.white === y.white && x.black === y.black

given [A: Zero]: Zero[ByColor[A]] with
def zero = ByColor(Zero[A].zero)

given [A: Monoid]: Monoid[ByColor[A]] with
def empty = ByColor(Monoid[A].empty)
def combine(x: ByColor[A], y: ByColor[A]) =
ByColor(Monoid[A].combine(x.white, y.white), Monoid[A].combine(x.black, y.black))

given Functor[ByColor] with
def map[A, B](fa: ByColor[A])(f: A => B): ByColor[B] = fa.map(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)

0 comments on commit 6d3a54e

Please sign in to comment.