scala - 如何将任意函数的 HList 应用于任意值?
问题描述
我希望能够将任意列表Function1[I, ?]
s 应用于任意 input I
。这是我到目前为止所拥有的:
type StringInputFunction[T] = Function[String, T]
val strLen: String => Int = _.length
val strRev: String => String = _.reverse
val functions = strLen :: strRev :: HNil
val expected = 4 :: "evif" :: HNil
object applyTo5 extends (StringInputFunction ~> Id) {
override def apply[T](f: StringInputFunction[T]): Id[T] = f("five")
}
def applyFunctionsTo5[FH <: HList, OH <: HList](fs: FH)
(implicit constrain: UnaryTCConstraint[FH, StringInputFunction],
mapper: Mapper.Aux[applyTo5.type, FH, OH]): mapper.Out = {
fs.map(applyTo5)
}
applyFunctionsTo5(functions) shouldBe expected
class ApplyTo(string: String) extends (StringInputFunction ~> Id) {
override def apply[T](f: StringInputFunction[T]): Id[T] = f(string)
}
def applyFunctionsTo[FH <: HList, OH <: HList]
(fs: FH, input: String)
(implicit constrain: UnaryTCConstraint[FH, StringInputFunction],
mapper: Mapper.Aux[ApplyTo, FH, OH]): mapper.Out = {
val applyTo = new ApplyTo(input)
fs.map(applyTo)
}
applyFunctionsTo(functions, "five") shouldBe expected
这会导致编译错误:
ShapelessSpec.scala:81: could not find implicit value for parameter mapper: shapeless.ops.hlist.Mapper[applyTo.type,FH]
fs.map(applyTo)
ShapelessSpec.scala:83: could not find implicit value for parameter mapper: shapeless.ops.hlist.Mapper.Aux[ApplyTo,shapeless.::[String => Int,shapeless.::[String => String,shapeless.HNil]],OH]
applyFunctionsTo(functions, "five") shouldBe expected
- 如何解决此问题以使用任何
String
输入? - 我可以进一步更改泛型以使用任何输入类型
T
吗?
解决方案
我在想我以前做过这个确切的操作,并且能够从几年前找到这个要点。总结一下我的示例,您可以仅使用 Shapeless 已经提供的操作很好地完成此操作,其方式看起来很像您在值级别对普通列表执行类似操作的方式。假设您有以下设置:
import shapeless.{ ::, HNil }
val strLen: String => Int = _.length
val strRev: String => String = _.reverse
val functions = strLen :: strRev :: HNil
然后你可以这样写:
scala> functions.zipApply(functions.mapConst("five"))
res0: Int :: String :: shapeless.HNil = 4 :: evif :: HNil
或这个:
scala> def foo(in: String) = functions.zipApply(functions.mapConst(in))
foo: (in: String)Int :: String :: shapeless.HNil
scala> foo("six")
res1: Int :: String :: shapeless.HNil = 3 :: xis :: HNil
这将适用于应用于该特定类型的特定类型的任何函数列表。
要点提供了一些替代方法,但zipApply
plusmapConst
对我来说是迄今为止最好的。
推荐阅读
- reactjs - 如何制作搜索栏reactjs
- c++ - 如何检查 Windows 中的静态库依赖项?
- tensorflow - Tensorflow text_generation 教程中对有状态 GRU 的误导性训练数据洗牌
- gradle - 如何在使用 gradle 构建分发 zip 文件后复制它?
- javascript - React Native 使用 Headless js 应用崩溃
- shell - 终端输入在 VM 或 x86 硬件上运行的 QNX 中不起作用
- excel - Excel - 同时计算两个值的匹配数
- python - PowerQueryConnection 进入 Python pandas 数据框
- c - MQTT over SSL 与 PAHO C
- kotlin - 用于创建想法 2019.3 中不存在的 kotlin 多平台项目的选项