我想以编程方式组合多个函数。如果这些函数都是同一类型,我可以执行以下操作:
def a(x: Int): Int = x+1
def b(y: Int): Int = y/2
def c(z: Int): Int = z*4
val f1 = (a _) andThen (b _) andThen (c _)
val f2 = List((a _), (b _), (c _)).reduce(_ andThen _)
此时f1
and f2
是同一件事,并且可以编译,因为List
定义了f2
is a List[Function1[Int,Int]]
但是,如果我想使用相同的基本归约技术将多个具有不同类型的兼容函数链接在一起,则会出现错误。
def d(x: Double): Int = x.toInt
def e(y: Int): String = y.toString
def f(z: String): Double = z.toDouble*4
//Works fine
val f3 = (d _) andThen (e _) andThen (f _)
//Doesn't compile
val f4 = List((d _), (e _), (f _)).reduce(_ andThen _)
第二个选项无法编译,因为定义的列表f4
被推断为List[Function1[Any,Any]]
,但我不知道是否有一种干净的类型安全方法来获取表单函数的有序集合Function1[A,B],Function1[B,C],Function1[C,D],...,Function1[X,Y]
并将它们粘在一起作为Function1[A,Y]
像这样。
有任何想法吗?