Scala函数与泛型的组合
我想用Scala函数与泛型的组合,scala,generics,functional-programming,Scala,Generics,Functional Programming,我想用将2个Scala函数组合成第3个,然后用将其组合成第3个,但是类型系统出现了问题 代码如下: object Test{ def process1[T](in : List[T]) : List[T] = in def process2[T](in : List[T]) : List[T] = in //this works fine but you have to read it inside out def combined2[T](in : List[T]) :
将2个Scala函数组合成第3个,然后用将其组合成第3个,但是类型系统出现了问题
代码如下:
object Test{
def process1[T](in : List[T]) : List[T] = in
def process2[T](in : List[T]) : List[T] = in
//this works fine but you have to read it inside out
def combined2[T](in : List[T]) : List[T] = process2(process1(in))
//this also works but at the cost of creating a new function every time
def combined3[T](in : List[T]) : List[T] = {
(process1[T] _ andThen process2[T] _)(in)
}
//this doesn't work. it is a function List[Nothing] => List[Nothing]
val combined = process1 _ andThen process2 _
def main(s : Array[String]) {
val input : List[Int] = List(1,2,3)
val out1 : List[Int] = process1(input)
val combinedOut2 : List[Int] = combined2(input)
val combinedOut3 : List[Int] = combined3(input)
//this will not compile as combined is [List[Nothing] => List[Nothing]
//val combinedOut : List[Int] = combined(input)
}
}
有没有一种很好的方法可以将combined
的值作为从List[T]
到List[T]
的函数,或者这是类型擦除的一个基本问题?不确定是否很好,但是combined3
可以缩短为:
def combined3[T] = process1[T] _ andThen process2[T] _
每次创建函数实例可能会针对每种情况进行优化:
val combinedInt = combined3[Int]
combinedInt(input)
您可以通过这种方式组合功能,它更干净
implicit class FunctionCombiner[T, U](fn: T => U) {
def &&&(f: T => U): T => U = {
(t: T) => {
fn(t); f(t)
}
}
}
在此之后,您可以运行如下语句:
val f1 = (i: Int) => println((1*i).toString)
val f2 = (i: Int) => println((2*i).toString)
val f3 = (i: Int) => println((3*i).toString)
val f = f1 &&& f2 &&& f3
f(5)
这将产生以下结果:
5
10
15
这是scala型系统的基本问题。我建议你从第2部分和第3部分开始阅读。无形状多态函数可以是一种解决方案