2

Another Scala Newbie question.

Trying to find the difference between:

def _1_sumUntil(n: Int) = (f: Int => Int) => (0 to n).toList.foldLeft(0){(a,b) => a + f(b)}

and

def _2_sumUntil(n: Int)(f: Int => Int) = (0 to n).toList.foldLeft(0){(a,b) => a + f(b)}

what is the advantage of one over the other (if at all) ?

user1189332
  • 1,773
  • 4
  • 26
  • 46
  • @om-nom-nom it's called "currying", not "carrying". http://stackoverflow.com/questions/36314/what-is-currying – Ionuț G. Stan Jul 31 '13 at 15:06
  • @IonuțG.Stan yep, sorry [mr. Curry](https://en.wikipedia.org/wiki/Haskell_Curry) :-( – om-nom-nom Jul 31 '13 at 15:07
  • if they both achieve the same effect, what is the advantage of one over the other? – user1189332 Jul 31 '13 at 15:14
  • @user1189332 unfortunately, in Scala, methods and functions are different beasts: http://jim-mcbeath.blogspot.ro/2009/05/scala-functions-vs-methods.html. See also this gist for a simple difference: https://gist.github.com/igstan/4d53408360cc826bd177 – Ionuț G. Stan Jul 31 '13 at 15:20

1 Answers1

3

The first is a method with one parameter list that returns a function from Int => Int to Int, the second is a method with two parameter lists that returns an Int.

Technically, by means of what is called eta-expansion—a method can be transparently converted to a function value—, the second method can be partially applied, yielding the same function as the first method:

val a = _1_sumUntil(33)    // (Int => Int) => Int
val b = _2_sumUntil(33) _  // (Int => Int) => Int   via eta-expansion

My advise is to use the second variant and avoid explicit function values. The advantage of the second is that—unless you do use eta-expansion—no function value is instantiated (apart from the function passed to foldLeft) which is then applied. Also it is arguably easier to read.

I would use the first version only if the main purpose of the method is really to give you a function from Int => Int to Int to pass around.


See also this question and this question.

Community
  • 1
  • 1
0__
  • 66,707
  • 21
  • 171
  • 266