# currying

In the two previous posts we learned what are:

1. function as first class citizen
2. 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
// 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
// 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
// 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.

1. function as first class citizen
2. closure
3. currying

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