0

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 :)

2
  • No. I don't think it same to much. In my question, parameter is a function :) Commented Sep 29, 2012 at 16:52
  • It doesn't make any difference, it's still the same question. Commented Sep 29, 2012 at 17:07

1 Answer 1

0

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

def transform(f: Double => Double)(input: Double) 

Can be seen as something that takes as a single argument a function Double => Double and returns another function that takes as a single argument a Double and returns a Double.

As Programming in Scala discusses, function currying also let's us do some nifty things, two of which come to mind are

  1. type inference
  2. new control abstractions

For type inference, consider something like foldLeft.

val myVector = Vector(1, 2, 3, 4) myVector.foldLeft(0.0)(_ + _) 

foldLeft is curried, and us specifying 0.0 as the initial value let's the type inferencer know we want our final result to be a Double.

For new control abstractions, we can do something like

def doWithFileAndClose(file: File)(func: () => Unit): Unit = try { func() } finally { file.close } 

which would be used like

doWithFileAndClose("somefile.txt") { /* do stuff */ } 

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 for and while loops.

Sign up to request clarification or add additional context in comments.

1 Comment

From declaration of the function transform we do not know that it returns Double.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.