Shapeless中TypeClass特征的emptyCoproduct和coproduct方法的目的是什么?

jed*_*sah 9 scala typeclass type-level-computation shapeless

我不完全清楚Shapeless 的特征emptyCoProductcoproduct方法的目的是什么TypeClass.

什么时候会使用这个TypeClass特性代替ProductTypeClass

这两种方法的实施方式有哪些例子?

Tra*_*own 20

假设我有一个简单的类型类:

trait Weight[A] { def apply(a: A): Int }

object Weight {
  def apply[A](f: A => Int) = new Weight[A] { def apply(a: A) = f(a) }
}
Run Code Online (Sandbox Code Playgroud)

还有一些例子:

implicit val stringWeight: Weight[String] = Weight(_.size)
implicit def intWeight: Weight[Int] = Weight(identity)
Run Code Online (Sandbox Code Playgroud)

案例类:

case class Foo(i: Int, s: String)
Run Code Online (Sandbox Code Playgroud)

和ADT:

sealed trait Root
case class Bar(i: Int) extends Root
case class Baz(s: String) extends Root
Run Code Online (Sandbox Code Playgroud)

我可以ProductTypeClass为我的类型类定义一个实例:

import shapeless._

implicit object WeightTypeClass extends ProductTypeClass[Weight] {
  def emptyProduct: Weight[HNil] = Weight(_ => 0)
  def product[H, T <: HList](hw: Weight[H], tw: Weight[T]): Weight[H :: T] =
    Weight { case (h :: t) => hw(h) + tw(t) }
  def project[F, G](w: => Weight[G], to: F => G, from: G => F): Weight[F] =
    Weight(f => w(to(f)))
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

scala> object WeightHelper extends ProductTypeClassCompanion[Weight]
defined object WeightHelper

scala> import WeightHelper.auto._
import WeightHelper.auto._

scala> implicitly[Weight[Foo]]
res0: Weight[Foo] = Weight$$anon$1@4daf1b4d

scala> implicitly[Weight[Bar]]
res1: Weight[Bar] = Weight$$anon$1@1cb152bb

scala> implicitly[Weight[Baz]]
res2: Weight[Baz] = Weight$$anon$1@74930887
Run Code Online (Sandbox Code Playgroud)

但!

scala> implicitly[Weight[Root]]
<console>:21: error: could not find implicit value for parameter e: Weight[Root]
              implicitly[Weight[Root]]
                        ^
Run Code Online (Sandbox Code Playgroud)

这是一个问题 - 它使我们的自动类型类实例派生对于ADT几乎无用.幸运的是我们可以使用TypeClass:

implicit object WeightTypeClass extends TypeClass[Weight] {
  def emptyProduct: Weight[HNil] = Weight(_ => 0)
  def product[H, T <: HList](hw: Weight[H], tw: Weight[T]): Weight[H :: T] =
    Weight { case (h :: t) => hw(h) + tw(t) }
  def project[F, G](w: => Weight[G], to: F => G, from: G => F): Weight[F] =
    Weight(f => w(to(f)))
  def emptyCoproduct: Weight[CNil] = Weight(_ => 0)
  def coproduct[L, R <: Coproduct]
    (lw: => Weight[L], rw: => Weight[R]): Weight[L :+: R] = Weight {
      case Inl(h) => lw(h)
      case Inr(t) => rw(t)
    }
}
Run Code Online (Sandbox Code Playgroud)

然后:

scala> object WeightHelper extends TypeClassCompanion[Weight]
defined object WeightHelper

scala> import WeightHelper.auto._
import WeightHelper.auto._

scala> implicitly[Weight[Root]]
res0: Weight[Root] = Weight$$anon$1@7bc44e19
Run Code Online (Sandbox Code Playgroud)

上面的所有其他东西仍然有效.

总结一下:Shapeless Coproduct是对ADT的一种抽象,通常你应该TypeClass为你的类型类提供实例,而不是只ProductTypeClass在可能的情况下.