假设我有两个元组,第一个是类型为值的元组(V1, V2, .., Vn)
,
第二个是类型为函数的元组(V1 => V1, V2 => V2, .., Vn => Vn)
。
现在我想将这两个元组(f1(v1), v2(v2), .., fn(vn))
与 type结合起来(V1, V2, .., Vn)
。
scala> val values = (1, 2.0, "3")
val values: (Int, Double, String) = (1,2.0,3)
scala> val funs = ((i: Int) => 2 * i, (f: Double) => 2 * f, (s: String) => s * 2)
val funs: (Int => Int, Double => Double, String => String) = ..
scala> val res = ??? // (2, 4.0, "33")
我不知道如何在scala 3.0(即dotty)中得到这个。
编辑:我查看了 shapeless 的源代码并得到了一个(部分工作)解决方案:
scala> trait Zip[V <: Tuple, F <: Tuple]{ type R <: Tuple; def apply(v: V, f: F): R }
scala> given Zip[Unit, Unit]{ type R = Unit; def apply(v: Unit, f: Unit): Unit = () }
scala> given [Hv, Hr, V <: Tuple, F <: Tuple](given z: Zip[V, F]): Zip[Hv *: V, (Hv => Hr) *: F] = new Zip {
| type R = Hr *: z.R
| def apply(v: Hv *: V, f: (Hv => Hr) *: F): R = {
| f.head(v.head) *: z.apply(v.tail, f.tail)
| }
| }
scala> val values = (1, 2.0, "3")
val values: (Int, Double, String) = (1,2.0,3)
scala> val funs = ((i: Int) => 2 * i, (f: Double) => 2 * f, (s: String) => s * 2)
val funs: (Int => Int, Double => Double, String => String) = ..
scala> def apply[V <: Tuple, F <: Tuple](v: V, f: F)(given z: Zip[V, F]): z.R = z.apply(v, f)
def apply[V <: Tuple, F <: Tuple](v: V, f: F)(given z: Zip[V, F]): z.R
scala> apply(values, funs)
val res0:
Zip[(Int, Double, String), (Int => Int, Double => Double, String => String)]#R = (2,4.0,33)
scala> val res: (Int, Double, String) = apply(values, funs)
1 |val res: (Int, Double, String) = apply(values, funs)
| ^^^^^^^^^^^^^^^^^^^
|Found: ?1.R
|Required: (Int, Double, String)
|
|where: ?1 is an unknown value of type Zip[(Int, Double, String), (Int => Int, Double => Double, String => String)]
我不知道为什么apply
方法的返回会丢失它的类型。