12/08

2018

Currying is a common technique in functional programming. It allows transforming a given function that takes multiple arguments into a sequence of functions, each having a single argument. Each of the resulting functions handles one argument of the original (uncurried) function and returns another function.

So, currying is a way to translate a function that takes a number of arguments into a chain of functions that each take a single argument. This may sound confusing, so let's look at a simple example:

fun subtract(x: Int, y: Int): Int { return x - y } println(subtract(50, 8))

This is a function that returns two arguments. The result is quite obvious. But maybe we would like to invoke this function with the following syntax instead:

subtract(50)(8)

We can return a function from another function:

fun subtract(x: Int): (Int) -> Int { return fun(y: Int): Int { return x - y } }

Here it is in the shorter form:

fun subtract(x: Int) = fun(y: Int): Int { return x - y }

And here it is in an even shorter form:

fun subtract(x: Int) = {y: Int -> x - y}

Although not very useful by itself, it's still an interesting concept to grasp.