如何使用 HList 现有成员创建类型类

How to create typeclass with HList existential member

我正在尝试创建模仿无形类型类的自定义类型类。它看起来像这样:

  trait View[Record] {
    type Result <: HList
    def apply(r: Record): Result
  }

  object View extends LowPriorityLiftFunction1{
    type Aux[Record, L <: HList] = View[Record] {type Result = L}
    implicit def atView[Record: View] = at[Record](implicitly[View[Record]].apply)
  }

假设我提供这样的功能:

object toHView extends ->( (_:Int) + 1)

implicit def provideView[Record, L <: HList]
(implicit generic: Generic.Aux[Record, L],
 mapper: Mapper[toHView.type, L])
: View.Aux[Record, mapper.Out] =
  new View[Record] {
    type Result = mapper.Out

    def apply(r: Record) = mapper(generic.to(r))
  }

所以如果我们定义:

case class Viewable(x: Int, y: Int, z : Int)
case class NotViewable(x: Int, y: Long, z : Int)

然后

val view = View(Viewable(1, 2, 3)) // is 2 :: 3 :: 4 :: HNil

val noView = View(NotViewable(1, 2, 3)) // is HNil

如果我尝试获取这里的麻烦

view.head

我有

Error:could not find implicit value for parameter c: IsHCons[View[Viewable]#Result]

我如何定义这个类型类以便以后有效地使用它的所有类型成员?

当然我可以去掉类型成员:

trait View[Record, Result <: HList] {
  def apply(r: Record): Result
}

object View extends LowPriorityLiftFunction1{
  implicit def atView[Record, Result]
  (implicit view: View[Record, Result]) = at[Record](view.apply)
}

object toHView extends ->((_: Int) + 1)
implicit def provideView[Record, L <: HList]
(implicit generic: Generic.Aux[Record, L],
 mapper: Mapper[toHView.type, L])
: View[Record, mapper.Out] =
  new View[Record, mapper.Out] {
    type Result = mapper.Out  

    def apply(r: Record) = mapper(generic.to(r))
  }

但从这一点开始

val view = View(Viewable(1, 2, 3))

我遇到“不明确的隐式值”问题

好的,这是:更改

implicit def atView[Record: View] = at[Record](implicitly[View[Record]].apply)

implicit def atView[Record](implicit v: View[Record]) = at[Record](v.apply(_))

原因是 implicitly 在处理精化类型成员时会失去精度,因此您的 HList(在本例中为 Int :: Int :: Int :: HNil)不是预期的精化类型,而是编译器吐出一个相当无用的 View#Result.

使用隐式参数而不是上下文绑定似乎可以保留改进后的类型。

此外,shapeless' theimplicitly 的替代方案,它保留了类型改进,although it doesn't seem to work in this case

这是 implicitly 丢失精度的示例,取自 the implementation in shapeless:

scala> trait Foo { type T ; val t: T }
defined trait Foo

scala> implicit val intFoo: Foo { type T = Int } = new Foo { type T = Int ; val t = 23 }
intFoo: Foo{type T = Int} = $anon$1@6067b682

scala> implicitly[Foo].t  // implicitly loses precision
res0: Foo#T = 23

scala> implicitly[Foo].t+13
<console>:13: error: type mismatch;
  found   : Int(13)
  required: String
              implicitly[Foo].t+13
                                 ^

scala> the[Foo].t         // the retains it
res1: Int = 23

scala> the[Foo].t+13
res2: Int = 36