如何使用 shapeless 连接函数参数和 return 值

How to concatenate function arguments and return values using shapeless

我试图在下面定义 compose 方法:

import shapeless.{::, HList, HNil}

def compose[A1 <: HList, R1, A2 <: HList, R2](f: A1 => R1, g: A2 => R2): R1 :: R2 :: HNil = ???

val f = (xs: Int :: String :: HNil) => xs.select[Int].toString + xs.select[String]
val g = (xs: Boolean :: HNil) => xs.select[Boolean]

// expected output:
// Int :: String :: Boolean :: HNil => String :: Boolean :: HNil
compose(f, g)

这是我的不完整代码,我不知道如何从 args 获取 A1A2。有人可以帮忙吗?

def compose[A1 <: HList, R1, A2 <: HList, R2](f: A1 => R1, g: A2 => R2)(implicit p: Prepend[A2, A1]) =
  (args: p.Out) => {
    val a1: A1 = ???
    val a2: A2 = ???
    f(a1) :: f(a2) :: HNil
  }

我能够通过 Split 实现一个可行的解决方案:

def compose[A1 <: HList, R1, A2 <: HList, R2, O <: HList, N <: Nat](f: A1 => R1, g: A2 => R2)(
  implicit split: Split.Aux[O, N, A1, A2]
): O => R1 :: R2 :: HNil = {
  (a: O) =>
    val (a1, a2) = split.apply(a)
    f(a1) :: g(a2) :: HNil //I assumed you meant calling g(a2) here
}

val f = (xs: Int :: String :: HNil) => xs.select[Int].toString + xs.select[String]
val g = (xs: Boolean :: HNil) => xs.select[Boolean]

val r: Int :: String :: Boolean :: HNil => String :: Boolean :: HNil = compose(f, g)

println(r.apply(1 :: "hello" :: true :: HNil)) // 1hello :: true :: HNil