|
Re: Partially applied functions
|
Posted: May 29, 2016 10:40 PM
|
|
What the author meant was you can't assign a function to a var or val. See line 10 below.
It seems you can pass a function to another function. However, that's only a "special case". A few pages later, the author said "If you are writing a partially applied function expression in which you leave off all parameters, such as println _ or sum _, you can express it more concisely by leaving off the underscore if a function is required at that point in the code". In other words, when you pass a function as a partially applied function to another function, you can pass it as is. (again, this is only a compiler trick, you are actually still passing square _, see line 17 below)
To be honest, I think this is kind of lame. In almost all functional programming languages, you can assign functions to vals or vars without the ugly trailing underscore.
1 object PartiallyAppliedFunction { 2 def square(x:Int) = x * x 3 4 def sumOfSquares(x:Int=>Int, a:Int, b:Int) = x(a) + x(b) 5 6 def main(args:Array[String]) { 7 println("hello world"); 8 9 // this line won't compile 10 // val squareAlias = square 11 12 // this line will compile 13 val squareAlias = square _ 14 15 println("square of 3 is: " + squareAlias(3)) 16 17 println(sumOfSquares(square _, 1,2)) 18 } 19 20 }
|
|