Reputation: 152
I have a function compose, that I know is correct
def compose[A,B,C](f: B => C, g: A => B): A => C = {
a: A => f(g(a))
}
But when I try to use it, I get an error
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.
Can someone please point out what am I doing wrong?
Upvotes: 2
Views: 1619
Reputation: 16324
You have a lot of options here! You can put parentheses around the parameter definitions:
compose((x: Int) => x+1, (y: Int) => y-1)(10)
Or put braces around the whole function:
compose({ x: Int => x+1 }, { y: Int => y-1 })(10)
Or specify the generic parameters explicitly. If you do it this way, you can even use the underscore syntax:
compose[Int, Int, Int](x => x+1, y => y-1)(10)
compose[Int, Int, Int](_+1, _-1)(10)
Or use type ascription, which also enables the underscore syntax:
compose({ x => x+1 }:(Int=>Int), { y => y-1 }:(Int=>Int))
compose({ _+1 }:(Int=>Int), { _-1 }:(Int=>Int))
Or combine some of these ideas into this, which is the shortest version I could find:
compose((_:Int)+1,(_:Int)-1)(10)
It's also worth mentioning that there already is a compose
method on Function1
:
({ x: Int => x+1 } compose { y: Int => y-1 })(10)
Upvotes: 5
Reputation: 24812
You need to add parenthesis around 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
Upvotes: 5