Currying in Scala
In our .net blog [shujaat.net], we have discussed about currying in details. Just to quote from there:
Currying is a transformation technique in functional programming space. It is used to convert a function with multiple parameters to a set of functions with single parameter each. It can be used to create refined algorithms where partial list of arguments can be provided to create more sophisticated operations. The nomenclature is in the honor of Haskell Curry, the creator of Haskell functional programming language. It must be remembered that the end-result of a curried version of a function should exactly be the same as its non-curried counterpart.
Let’s consider a simple function. The function has three parameters of type Double. It just adds them and returns the result. We don’t know how this function was implemented as such but just think of it as a given and it would ease the pain 🙂
Unlike C#, Scala has an in-built support for currying. You can just call curried on a function definition and get your function to its curried counterpart, which is a series of single arguments functions. In the following image, we are calling curried, and hey look at the intellisense. It clearly shows what it would do to our function. It would convert add into a series of single parameter functions of Double type. At the end, it would return the result, which would also be of Double type.
Let’s use the curried version of our add function. Every function in the series of functions results in another Function1 except for the last one, which result in a Double type.
Let’s see exactly, how this series is being used by scala. Look at the transformations into different Function1 (s) and see how sum is assigned a value of type Double.
The opposite of currying is un-currying and scala definitely supports it. Here we are converting our curried add function back to its uncurried format. It accepts three parameters of double type and returns a result of type Double.
What about currying and method overloading?
For currying, it seems impossible to support function overloading in scala based on the syntax we discussed above. Scala has another syntax for currying where we just specify the number of arguments. We can use that syntax for currying in case of overloading. Although there is more typing involved with using that syntax, but that is the only way, unfortunately 🙁
This syntax is practically equivalent of the syntax we discussed above. This works in case when we don’t have an overload. In case of an overload, we have to declare it like a partial function (discussed later), otherwise, we get the following compile time failure:
Here we have two add functions with different parameters list. Here we need to specify the details of the parameters if we are to generate the curried versions.