gpt4 book ai didi

scala - 再次在 HLists 上进行映射

转载 作者:行者123 更新时间:2023-12-02 03:34:58 24 4
gpt4 key购买 nike

我已经通过这里的一些关于同一问题的问题,但似乎无法为我的案例找到解决方案。

本质上,我需要定义一个接受 x 的方法,其中 x <: T 和一个 l,其中 L <: HList 并使用从 T 继承的每个可能类中定义的 Poly1 映射到 l。

我尝试了多种方法,最后一次尝试导致了一些非常可怕的 scalac 炸弹。我一定是在做一些非常愚蠢的事情,但我似乎无法理解它!

import shapeless._
import ops.hlist._

trait T {
val fun: Poly1
}
case class C() extends T {
object fun extends Poly1 {
implicit val caseInt = at[Int](i => "int " + i)
override def toString = "here I am, poly1"
}
}
def method[X <: T](x: X) = x.fun
method(C())
res0: shapeless.Poly1 = here I am, poly1

def method2[X <: T, L <: HList](x: X, l: L)(implicit m: Mapper[x.fun.type, L]) = l map x.fun
method(C(), 23 :: HNil) //BOOM!

最佳答案

我不知道这是否正是您想要的,但它有效:

object test {

import shapeless._
import ops.hlist._

trait T {

type PT <: Singleton with Poly1
val fun: PT
}

object C extends T {

type PT = funImpl.type
object funImpl extends Poly1 {
implicit val caseInt = at[Int](i => "int " + i)
override def toString = "here I am, poly1"
}
val fun = funImpl
}

case class D() extends T {

type PT = funImpl.type
object funImpl extends Poly1 {
implicit val caseInt = at[Int](i => "int " + i)
override def toString = "here I am, poly1"
}
val fun = funImpl
}


def method[X <: T](x: X) = x.fun
val ok = method(C)

// singletonize it
implicit def toOps[X <: T](x: X): Method2Ops[x.type] = { Method2Ops(x: x.type) }
case class Method2Ops[X <: Singleton with T](val x: X) {

def method2[L <: HList](l: L)(implicit m: Mapper[X#PT, L]) = l map (x.fun: X#PT)
}

val okC = C method2 (23 :: HNil)

val d = D()

val okD = d method2 (23 :: HNil)
}

关于scala - 再次在 HLists 上进行映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24130986/

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