2

I am on my way to learning Scala after coming from different programming languages (mostly interpreted). I am doing the following exercise and I get an error.

def sum(f: Int => Int)(a: Int, b: Int): Int = {
    def loop(a: Int, acc: Int): Int = {
      if (a >= b) acc
      else loop(a+1, f(a) + acc)
    }
    loop(a, 0)
 }
 sum(x => x * x, 2, 4) //Too many arguments  

I can't see what is wrong there?

om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
Andrew
  • 6,254
  • 16
  • 59
  • 93

3 Answers3

5

If you declare your function with multiple parentheses (multiple argument lists), you also have to call it like that (curried form):

sum(x => x * x)(2, 4)

See What's the difference between multiple parameters lists and multiple parameters per list in Scala? for more information.

Community
  • 1
  • 1
rolve
  • 10,083
  • 4
  • 55
  • 75
4

The function must be called in the explicitly curried form (there must be a better name) because that is how it is defined:

sum(x => x * x)(2, 4)

//def sum (f: Int => Int) (a: Int, b: Int):
//    sum (x => x * x)    (2,      4)

But this is also neat, because only one part of the curried form must be evaluated at a time:

val sumOfSquares = sum(x => x * x)
val s = someOfSquares(2,4)
3

You have defined sum with two parameter lists but are trying to call it with just one.

The syntactically correct way to call it would be sum(x => x * x)(2, 4)

Ben James
  • 121,135
  • 26
  • 193
  • 155