2014-11-06 60 views
0

我想结合2斯卡拉功能到第3与andThen但我遇到类型系统的问题。斯卡拉与泛型的函数组合

下面是代码:

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]或这是与类型擦除一个根本性的问题?

+1

这是斯卡拉型系统的根本问题。我建议你从http://www.chuusai.com/2012/04/27/shapeless-polymorphic-function-values-1/开始阅读第2和3部分。无形状多态函数可以是一个解决方案 – 2014-11-06 06:03:15

回答

1

不知道这是很好的,但combined3可以缩短为:功能情况的

def combined3[T] = process1[T] _ andThen process2[T] _ 

创建每次可以针对每种情况进行优化:

val combinedInt = combined3[Int] 

combinedInt(input) 
0

您可以结合功能这样,它更清洁

implicit class FunctionCombiner[T, U](fn: T => U) { 
    def &&&(f: T => U): T => U = { 
     (t: T) => { 
      fn(t); f(t) 
     } 
    } 
} 

在此之后,您可以运行stat对此语句,如:

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