如何将任意函数的HList应用于任意值?

时间:2019-06-20 15:27:56

标签: scala shapeless

我希望能够将Function1[I, ?]的任意列表应用于任意输入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
  1. 如何解决此问题以使其与任何String输入一起使用?
  2. 我是否可以进一步更改通用化,以使其适用于任何输入类型T

1 个答案:

答案 0 :(得分:5)

我以为我以前做过这种精确的手术,几年前就能找到this gist。总结一下我的示例,您可以仅使用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加上mapConst对我来说是最好的。