# currying

In the two previous posts we learned what are:

- function as first class citizen
- closure

In this post we are modifying our combination of these two concepts to a very powerful pattern named **currying**.

Here is our previous example.

```
// add is a binary function, it has two parameters
function add( a, b ){
// sum is a nullary function, it is not parameters
function sum(){
// capturing a and b by reference
return a + b;
}
return sum();
}
```

### function arguments

There are names for number of arguments a function takes, which is called **arity** of that function.

**nullary function**: a function that accepts no arguments e.g. sum().**unary function**: a function that accepts just one argument e.g. add( a ).**binary function**: a function that accepts two arguments e.g. add( a, b ).**trinary function**: a function that accepts three arguments e.g. shape( x, y, z ).**n-ary function**: a function that accepts more then three (4, 5, etc) arguments e.g. Math.max( a, b, c, d, e )**variadic function**: a function that accepts arbitrary arguments e.g add( ...args ).

And you can guess that the arity of our add() function is 2, or it is a binary function.

### unary function

While we have many choices in terms of arity for a function, but the best one for us is **unary function**.

Using **closure** feature of JS we can spread a function arguments to some unary function that each one takes just one argument, and therefore, each nested function takes next argument.

Lets convert our add( a, b )) function to a curry function.

First removing pointless expressions

```
// add is a binary function, it has two parameters
function add( a, b ){
// sum is a nullary function, it is not parameters
return function(){
// capturing a and b by reference
return a + b;
}
}
```

Second, making all functions, unary, or all with arity of one.

```
// add is a unary function
function add( a ){
// sum is a unary function
return function( b ){
// capturing a and b by reference
return a + b;
}
}
```

ES6 style.

`const add = a => b => a + b; `

Lets test it.

```
add( 2 ); // function add()
add( 2 )( 3 ); // 5
```

That is it. We converted our first binary function to a unary function.

And now everything is ready to go to next step which is **partial application**.

Thus remember so far that we are using three things.

- function as first class citizen
- closure
- currying

And in next post we will add partial application to this mix.

More about variadic function if you liked.

*Update: Mon Nov 04 2019 09:56:14 GMT+0330 (Iran Standard Time)*