我想用andThen将2个Scala函数组合成第三个函数,但是类型系统遇到了问题。
以下是代码:
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],或者这是类型擦除的一个基本问题?
发布于 2014-11-06 12:51:49
不确定它是否不错,但可以将combined3缩短为:
def combined3[T] = process1[T] _ andThen process2[T] _每次创建函数实例都可以针对每种情况进行优化:
val combinedInt = combined3[Int]
combinedInt(input)发布于 2016-04-16 06:22:09
你可以用这种方式组合功能,它更干净
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
15https://stackoverflow.com/questions/26772270
复制相似问题