# Currying

*A brief intro to currying*

We have the following function.

```
def add(x: Int, y: Int): Int = {
x + y
}
```

with the following signature

```
add: (x: Int, y: Int)Int
```

That is, `add`

is a map from the space of integer 2-tuples to the space of integers.

We say the function has an `arity`

of `n`

or is an `n-ary`

function if it takes `n`

arguments.

`add`

is a `2-ary`

or `binary`

function.

A function that takes a single argument is called a *unary* function.

The fundamental question of currying is this

Can we decompose an

`n-ary`

function into`n`

unary functions?

In the case of the above example, the question is if we can decompose a binary function into two unary functions.

The answer is yes. Here is how.

We can define

```
def add(x: Int) = {
def addX(y: Int) = {
x + y
}
addX _
}
```

Alternatively we could write

```
def add(x: Int) = (y: Int) => {
x + y
}
```

`add`

is now a unary function that maps an integer `x`

to another unary function `addX`

that maps `y`

to `x + y`

.

`add`

now has the following signature.

```
(x: Int)Int => Int
```

`add(1)(1)`

is then equivalent to the previous `add(1,1)`

.

In general, given an n-ary function `f`

, we can define a function `g`

that is a composition of n unary functions. This process is referred to as *currying*.

```
val f = (a: Int, b: Int) = a + b
val g = f.curried
```

Note that each of these unary functions themselves return functions, making them higher order.