Scala组合函数



我有一个函数compose,我知道它是正确的

def compose[A,B,C](f: B => C, g: A => B): A => C = {
    a: A => f(g(a))
}

但当我尝试使用它时,我会收到一个错误

def main(args: Array[String]): Unit = {
    println("Function composition:")
    compose(x: Int => x+1, y: Int => y-1)(10)
}
error: identifier expected but integer literal found.

有人能指出我做错了什么吗?

您需要在x: Int/y:Int:周围添加括号

scala> compose((x: Int) => x+1, (y: Int) => y-1)(10)
res34: Int = 10
scala> def main(args: Array[String]): Unit = {
     |     compose((x: Int) => x+1, (y: Int) => y-1)(10)
     | }
main: (args: Array[String])Unit

这里有很多选项!您可以在参数定义周围加括号:

compose((x: Int) => x+1, (y: Int) => y-1)(10)

或者在整个函数周围加括号:

compose({ x: Int => x+1 }, { y: Int => y-1 })(10)

或者显式指定泛型参数。如果你这样做,你甚至可以使用下划线语法:

compose[Int, Int, Int](x => x+1, y => y-1)(10)
compose[Int, Int, Int](_+1, _-1)(10)

或者使用类型归属,这也启用了下划线语法:

compose({ x => x+1 }:(Int=>Int), { y => y-1 }:(Int=>Int))
compose({ _+1 }:(Int=>Int), { _-1 }:(Int=>Int))

或者将其中的一些想法结合到这个中,这是我能找到的最短的版本:

compose((_:Int)+1,(_:Int)-1)(10)

还值得一提的是,在Function1:上已经有了compose方法

({ x: Int => x+1 } compose { y: Int =>  y-1 })(10)

最新更新