Reputation: 4562
The following two higher-order functions yield the same result, but I'm having trouble understanding the difference between the two. In fact, I don't understand 1). How can a function have two sets of ()
?
1)
def sum(f: Int => Int) (a: Int, b: Int) = {
def loop(a: Int, acc: Int) : Int =
if (a > b) acc
else loop (a + 1, f(a) + acc)
loop (a, 0)
}
2)
def sum(f: Int => Int, a: Int, b: Int) = {
def loop(a: Int, acc: Int) : Int =
if (a > b) acc
else loop (a + 1, f(a) + acc)
loop (a, 0)
}
Upvotes: 4
Views: 157
Reputation: 23532
The first function is curried. Meaning you can partially apply it more easily. If you only use the first parameter list the function returns another function with the signature (Int, Int) => Int
.
This is really useful if you need to pass a function with a specific function signature to higher order functions like map
or reduce
.
In other functional programming languages like Haskell, all functions are curried by default. I wrote a whole blog post on this topic in case you're interested. You can read it right here.
Upvotes: 3