JavaScript the Fun Part


functional-programming-javascript

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
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.

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.

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