使用子类型在类上创建Scalaz等实例

时间:2015-05-14 16:15:37

标签: scala scalaz

我有以下简单的ADT,如何在不使用显式模式匹配所有可能的组合的情况下实现相等类型类的实例?

import scalaz._
import Scalaz._

sealed trait Billinginfo
case class CreditCard(number: Int, holder: String, Address: String) extends Billinginfo
case object COD extends Billinginfo
case class Invoice(cId: String) extends Billinginfo

object Billinginfo{

  implicit val BillingEqual = Equal.equal[Billinginfo]{(b1,b2) =>
    (b1,b2) match {
      case (Invoice(c1), Invoice(c2)) => c1 === c2
      case (CreditCard(a,b,c), CreditCard(d,e,f)) =>
        a === d &&
        b === e &&
        c === f //writing exhaustive match would be tedious
    }
  }

1 个答案:

答案 0 :(得分:4)

你(至少)有两个选择。一个是使用“自然”平等。如果您没有案例类成员的任何自定义类型,这应该可以正常工作:

implicit val BillingEqual: Equal[Billinginfo] = Equal.equalA[Billinginfo]

或者您可以使用Shapeless的类型类实例派生:

import shapeless._
import scalaz.{ Coproduct => _, :+: => _, _ }, Scalaz._

object EqualDerivedOrphans extends TypeClassCompanion[Equal] {
  object typeClass extends TypeClass[Equal] {
    def product[H, T <: HList](eh: Equal[H], et: Equal[T]): Equal[H :: T] =
      tuple2Equal(eh, et).contramap {
        case h :: t => (h, t)
      }

    def project[A, B](b: => Equal[B], ab: A => B, ba: B => A): Equal[A] =
      b.contramap(ab)

    def coproduct[L, R <: Coproduct](
      el: => Equal[L],
      er: => Equal[R]
    ): Equal[L :+: R] = eitherEqual(el, er).contramap {
      case Inl(l) => Left(l)
      case Inr(r) => Right(r)
    }

    val emptyProduct: Equal[HNil] = Equal.equal((_, _) => true)
    val emptyCoproduct: Equal[CNil] = Equal.equal((_, _) => true)
  }
}

import EqualDerivedOrphans._

这将为任何具有Equal个实例的案例类派生Equal个实例。

当然,你可以列举这些案件,实际上并不是那么可怕:

implicit val BillingEqual = Equal.equal[Billinginfo] {
  case (Invoice(c1), Invoice(c2)) => c1 === c2
  case (CreditCard(a, b, c), CreditCard(d, e, f)) =>
    a === d && b === e && c === f
  case (COD, COD) => true
  case _ => false
}

请注意,您不需要元组上的额外匹配级别。