如何将单独的函数应用于已知Shapels HList的每个索引



我知道HList的类型,我想将特定函数应用于HList中的每个特定项。例如

我知道HList的类型,在这种情况下是String::Int::String::HNil

val values = "Hello World" :: 5 :: "Goodbye World" :: HNil

所以我从type=>每个项目的Int。

val funcs =
((_: String) => 1) ::
((_: Int) => 2) ::
((_: String) => 3) ::
HNil

我想将函数1应用于值1,将函数2应用于值2,等等。这是对函数签名的最佳猜测。V

// V are the Values of type String :: Int :: String :: HNil
// F are the Functions of type (String => Int) :: (Int => Int) :: (String => Int) :: HNil
// R is the Int Results of type Int :: Int :: Int :: HNil
def applyFunction[V <: HList, F <: HList, R <: HList](v: V, f: F)(
implicit ev: V =:= F,
utcc: UnaryTCConstraint[F, Function[*, Int]]
): R

现在我正在努力解决如何真正实现这个功能,或者Shapeless是否已经有了这样的功能。

利用这个SO答案作为灵感,我得出了以下结果:

import shapeless._
val values = "Hello World" :: 5 :: "Goodbye World" :: HNil
val funcs = ((_: String) => 1) ::
((_: Int) => 2) ::
((_: String) => 3) :: HNil
object applyTo extends Poly1 {
implicit def caseInt = at[(Int=>Int,Int)]      {case (f,v) => f(v)}
implicit def caseStr = at[(String=>Int,String)]{case (f,v) => f(v)}
}
funcs.zip(values).map(applyTo)
//1 :: 2 :: 3 :: HNil: Int :: Int :: Int :: shapeless.HNil

您可以使用标准类型类shapeless.ops.hlist.ZipApply

funcs.zipApply(values) // 1 :: 2 :: 3 :: HNil

最新更新