Possible Duplicate:
What's the rationale behind curried functions in Scala?
I have two difference ways to declare a function: 1) use currying. 2)use function as parameter.
Here is my code :
def transform(f: Double => Double)(input: Double) = {
f(input)
}
def transformVer2(f: Double => Double, input: Double) = {
f(input)
}
transform(x=>x*x)(10) //> res8: Double = 100.0
transformVer2(x=>x*x, 10) //> res9: Double = 100.0
I don’t know what the real difference of two above declare of a function. Please tell me.
Thanks 🙂
The former employs currying, the latter is something you’re probably more familiar with from languages like C, C++, etc.
Currying is something that is prominent in functional programming languages.. functional programming languages place the idea of functions and function chaining in high regard so something like
Can be seen as something that takes as a single argument a function
Double => Doubleand returns another function that takes as a single argument aDoubleand returns aDouble.As Programming in Scala discusses, function currying also let’s us do some nifty things, two of which come to mind are
For type inference, consider something like
foldLeft.foldLeftis curried, and us specifying0.0as the initial value let’s the type inferencer know we want our final result to be aDouble.For new control abstractions, we can do something like
which would be used like
This takes advantage that Scala will accept curly braces in place of parentheses, which makes the above look just like familiar control structures such as
forandwhileloops.