Currying in Scala
Abstractions, combined with higher-order functions, can be used to create new abstractions that improve the computational power of a programming language.
Suppose we define a few summation functions:
While these functions are already quite simple, the methods appear redundant. Is there a way to generalize them?
One option is to reduce the number of parameters passed into these functions. We can abstract functions using a technique called currying. Currying is a form of function abstraction where a function that takes in multiple arguments is reconstructed into a series of functions, where each function takes in a single argument. To support this method, the Scala programming language allows us to pass in function arguments.
We see that our summation functions are very similar. Update the function
sum to a more general function.
Rewrite the summation functions using our new general function
To evaluate a sum of cubes bounded from 1 to 10, now we simply call
That is an improvement. However, each function is still very specific to a particular summation problem. Let’s abstract our functions even further.
We do not need to create independent summation functions. Instead, we can use the general summation function that we defined previously. To calculate a sum of cubes from 1 to 10, we write:
A function with multiple parameters:
n > 1 is equivalent to:
g is a fresh identifier.
Functional Programming Principles in Scala