Scala组成函数

Mik*_*iku 1 scala

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

def compose[A,B,C](f: B => C, g: A => B): A => C = {
    a: A => f(g(a))
}
Run Code Online (Sandbox Code Playgroud)

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

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.
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*rth 5

您需要在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
Run Code Online (Sandbox Code Playgroud)


Ben*_*ich 5

你有很多选择!您可以在参数定义周围加上括号:

compose((x: Int) => x+1, (y: Int) => y-1)(10)
Run Code Online (Sandbox Code Playgroud)

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

compose({ x: Int => x+1 }, { y: Int => y-1 })(10)
Run Code Online (Sandbox Code Playgroud)

或者明确指定通用参数.如果你这样做,你甚至可以使用下划线语法:

compose[Int, Int, Int](x => x+1, y => y-1)(10)
compose[Int, Int, Int](_+1, _-1)(10)
Run Code Online (Sandbox Code Playgroud)

或者使用类型ascription,它还启用下划线语法:

compose({ x => x+1 }:(Int=>Int), { y => y-1 }:(Int=>Int))
compose({ _+1 }:(Int=>Int), { _-1 }:(Int=>Int))
Run Code Online (Sandbox Code Playgroud)

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

compose((_:Int)+1,(_:Int)-1)(10)
Run Code Online (Sandbox Code Playgroud)

还值得一提的是,已有一种compose方法Function1:

({ x: Int => x+1 } compose { y: Int =>  y-1 })(10)
Run Code Online (Sandbox Code Playgroud)