对于无形的新手,我对使用需要一些依赖性的多态函数有疑问.我基本上有这个代码,并希望从run方法中拉出somePoly对象:
import shapeless._
object SomeObject {
type SomeType = Int :+: String :+: (String, Int) :+: CNil
def run( someList: List[SomeType], someInt:Int, someWord:String ) = {
object somePoly extends Poly1 {
implicit def doIt = at[Int]( i => i + someInt + someWord.length)
implicit def doIt2 = at[String]( i => i.length + someWord.length)
implicit def doIt3 = at[(String, Int)]( i => i._1.length + someWord.length)
}
someList.map( _.map(somePoly) )
}
}
Run Code Online (Sandbox Code Playgroud)
我想这样做的一种方式就是这样,但它似乎很乱:
object TypeContainer {
type SomeType = Int :+: String :+: (String, Int) :+: CNil
}
case class SomePolyWrapper( someList: List[TypeContainer.SomeType], someInt:Int, someWord:String ){
object somePoly extends Poly1 {
implicit def doIt = at[Int]( i => i + someInt + someWord.length)
implicit def doIt2 = at[String]( i => i.length + someWord.length)
implicit def doIt3 = at[(String, Int)]( i => i._1.length + someWord.length)
}
}
object SomeObject {
def run( someList: List[TypeContainer.SomeType], someInt:Int, someWord:String ) = {
val somePolyWrapper = SomePolyWrapper(someList, someInt, someWord)
someList.map( _.map(somePolyWrapper.somePoly) )
}
}
Run Code Online (Sandbox Code Playgroud)
有人有什么建议吗?
Scala 隐式解析系统的局限性意味着Poly定义需要是一个稳定的标识符,这使得这种事情比应有的更加痛苦。正如我在 Gitter 上提到的,我知道有几种解决方法(可能还有其他方法)。
一种方法是创建Poly1a PolyN,其中额外的参数用于someInt和someWord值。如果您要在 上进行映射HList,则可以使用mapConst和来zip使输入HList具有正确的形状。我从来没有为联产品做过这样的事情,但类似的东西可能会起作用。
另一种方法是使用自定义类型类。在你的情况下,可能看起来像这样:
import shapeless._
trait IntFolder[C <: Coproduct] {
def apply(i: Int, w: String)(c: C): Int
}
object IntFolder {
implicit val cnilIntFolder: IntFolder[CNil] = new IntFolder[CNil] {
def apply(i: Int, w: String)(c: CNil): Int = sys.error("Impossible")
}
def instance[H, T <: Coproduct](f: (H, Int, String) => Int)(implicit
tif: IntFolder[T]
): IntFolder[H :+: T] = new IntFolder[H :+: T] {
def apply(i: Int, w: String)(c: H :+: T): Int = c match {
case Inl(h) => f(h, i, w)
case Inr(t) => tif(i, w)(t)
}
}
implicit def iif[T <: Coproduct: IntFolder]: IntFolder[Int :+: T] =
instance((h, i, w) => h + i + w.length)
implicit def sif[T <: Coproduct: IntFolder]: IntFolder[String :+: T] =
instance((h, i, w) => h.length + i + w.length)
implicit def pif[T <: Coproduct: IntFolder]: IntFolder[(String, Int) :+: T] =
instance((h, i, w) => h._1.length + i + w.length)
}
Run Code Online (Sandbox Code Playgroud)
然后你可以编写一个更通用的版本run:
def run[C <: Coproduct](
someList: List[C],
someInt: Int,
someWord: String
)(implicit cif: IntFolder[C]): List[Int] = someList.map(cif(someInt, someWord))
Run Code Online (Sandbox Code Playgroud)
并像这样使用它:
scala> run(List(Coproduct[SomeType](1)), 10, "foo")
res0: List[Int] = List(14)
scala> run(List(Coproduct[SomeType](("bar", 1))), 10, "foo")
res1: List[Int] = List(16)
Run Code Online (Sandbox Code Playgroud)
操作的特殊性使得这种方法看起来有点奇怪,但如果我真的需要对不同的联产品做这样的事情,这可能是我会选择的解决方案。