scala - 如何将单独的函数应用于已知 Shapelss 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 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
推荐阅读
- android - GeckoView 发送事件或启动函数 (Android)
- verilog - Verilog 中的“当前模拟时间”和事件队列到底是什么?
- ios - CGContext 在 UIImage 的错误部分绘制
- makefile - 为什么 make 不迭代我的源文件?
- javascript - 在angular js的控制器中添加自定义服务的正确方法是什么?
- reactjs - 使用 Detox 检查禁用按钮状态
- angular - Angular Adminlte - 部署中的 LoadscriptDirective 问题
- sqlite - 使用 python 中的 SQL 语句在 SQL LITE 中添加一个列到一定数量
- python-3.x - 添加类成员变量时如何避免重写派生类?
- python - 在 Django 中,当我更新发布日期时,如何从 get_absolute_url 获取链接已更新?