Scala Currying & Partially Applied Functions

Currying is a concept rooted in mathematics and has also found it is way in computer science. Currying is a process of translating a function taking multiple arguments to a set of functions accepting only one argument. It is named after Haskell Curry! Currying in computer science is also done in a similar manner. You can read more on the background here.

h(x)(y)(z) = f(x,y,z)

h = curry(f)

Let’s see how we can apply currying in Scala. Well, it’s not difficult to curry a function. See Below

//Function as we know it.
def addRegular(x:Int, y:Int) = x + y

//Same function but Currying applied
def addCurried(x:Int)(y:Int) = x + y
val result = addCurried(10)(20)
println(result)

If you just pass addCurried(10) you would get an error. Which is not good and to be fair the function did require all the parameters to evaluate. Getting around this is simple with partially applied functions, these should not be confused with partial functions. See Below

//Same function but Currying applied
def addCurried(x:Int)(y:Int) = x + y
val result1 = addCurried(10)(_)
//Another way with shorter syntax
val result2 = addCurried(10)_
//Does not give an error but says resul1 is a function
println(result1)

Another example of a partially applied function

//Same function but Currying applied
def addCurried(x:Int)(y:Int) = x + y + z
val add = addCurried(10)(_)(30)
val result = add(20)
//Does gives the result as 10+20+30=60
println(result1)

How about currying an existing function. That is also possible via Function.curried. It converts a function of N parameters to a curried function of order N. See Below

//Function as we know it.
def multiplyRegular(x:Int, y:Int) = x + y

val multiplyCurried = Function.curried(multiplyRegular _)
val anotherCurried = multiplyRegular.curried
val result = multiplyCurried(10)(20)
println(result)

Currying is a powerful feature in Functional Programming languages like Haskell. Though its usage may be questioned in Scala due to the hybrid nature of the language. However, it can prove to be a valuable tool, when applying them to collections using transforming functions like map, reduce, fold etc..

Till next time!

Leave a Comment