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

4

1 Answer 1

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.