gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:31:20 25 4
gpt4 key购买 nike

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

  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(_))

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

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

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

这是一个隐式丢失精度的例子,取自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

关于scala - 如何使用 HList 现有成员创建类型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31747143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com