Chapter 4. Implementing Functional Programming Techniques in JavaScript

Hold on to your hats because we're really going to get into the functional mind-set now.

In this chapter, we're going to do the following:

  • Put all the core concepts together into a cohesive paradigm
  • Explore the beauty that functional programming has to offer when we fully commit to the style
  • Step through the logical progression of functional patterns as they build upon each other
  • All the while, we will build up a simple application that does some pretty cool stuff

You may have noticed a few concepts that were brought up in the last chapter when dealing with functional libraries for JavaScript, but not in Chapter 2, Fundamentals of Functional Programming. Well, that was for a reason! Compositions, currying, partial application, and more. Let's explore why and how these libraries implemented those concepts.

Functional programming can come in a variety of flavors and patterns. This chapter will cover many different styles of functional programming:

  • Data generic programming
  • Mostly functional programming
  • Functional reactive programming and more

This chapter, however, will be as style-unbiased as possible. Without leaning too hard on one style of functional programming over another, the overall goal is to show that there are better ways to write code than what is often accepted as the correct and only way. Once you free your mind about the preconceptions of what is the right way and what is not the right way to write code, you can do whatever you want. When you just write code with childlike abandon for no reason other than the fact that you like it and when you're not concerned about conforming to the traditional way of doing things, then the possibilities are endless.

Partial function application and currying

Many languages support optional arguments, but not in JavaScript. JavaScript uses a different pattern entirely that allows for any number of arguments to be passed to a function. This leaves the door open for some very interesting and unusual design patterns. Functions can be applied in part or in whole.

Partial application in JavaScript is the process of binding values to one or more arguments of a function that returns another function that accepts the remaining, unbound arguments. Similarly, currying is the process of transforming a function with many arguments into a function with one argument that returns another function that takes more arguments as needed.

The difference between the two may not be clear now, but it will be obvious in the end.

Function manipulation

Actually, before we go any further and explain just how to implement partial application and currying, we need a review. If we're going to tear JavaScript's thick veneer of C-like syntax right off and expose it's functional underbelly, then we're going to need to understand how primitives, functions, and prototypes in JavaScript work; we would never need to consider these if we just wanted to set some cookies or validate some form fields.

Apply, call, and the this keyword

In pure functional languages, functions are not invoked; they're applied. JavaScript works the same way and even provides utilities for manually calling and applying functions. And it's all about the this keyword, which, of course, is the object that the function is a member of.

The call() function lets you define the this keyword as the first argument. It works as follows:

console.log(['Hello', 'world'].join(' ')) // normal way
console.log(Array.prototype.join.call(['Hello', 'world'], ' ')); // using call

The call() function can be used, for example, to invoke anonymous functions:

console.log((function(){console.log(this.length)}).call([1,2,3]));

The apply() function is very similar to the call() function, but a little more useful:

console.log(Math.max(1,2,3)); // returns 3
console.log(Math.max([1,2,3])); // won't work for arrays though
console.log(Math.max.apply(null, [1,2,3])); // but this will work

The fundamental difference is that, while the call() function accepts a list of arguments, the apply() function accepts an array of arguments.

The call() and apply() functions allow you to write a function once and then inherit it in other objects without writing the function over again. And they are both members themselves of the Function argument.

Note

This is bonus material, but when you use the call() function on itself, some really cool things can happen:

// these two lines are equivalent
func.call(thisValue);
Function.prototype.call.call(func, thisValue);

Binding arguments

The bind() function allows you to apply a method to one object with the this keyword assigned to another. Internally, it's the same as the call() function, but it's chained to the method and returns a new bounded function.

It's especially useful for callbacks, as shown in the following code snippet:

function Drum(){
  this.noise = 'boom';
  this.duration = 1000;
  this.goBoom = function(){console.log(this.noise)};
}
var drum = new Drum();
setInterval(drum.goBoom.bind(drum), drum.duration);

This solves a lot of problems in object-oriented frameworks, such as Dojo, specifically the problems of maintaining the state when using classes that define their own handler functions. But we can use the bind() function for functional programming too.

Tip

The bind() function actually does partial application on its own, though in a very limited way.

Function factories

Remember our section on closures in Chapter 2, Fundamentals of Functional Programming? Closures are the constructs that makes it possible to create a useful JavaScript programming pattern known as function factories. They allow us to manually bind arguments to functions.

First, we'll need a function that binds an argument to another function:

function bindFirstArg(func, a) {
  return function(b) {
    return func(a, b);
  };
}

Then we can use this to create more generic functions:

var powersOfTwo = bindFirstArg(Math.pow, 2);
console.log(powersOfTwo(3)); // 8
console.log(powersOfTwo(5)); // 32

And it can work on the other argument too:

function bindSecondArg(func, b) {
  return function(a) {
    return func(a, b);
  };
}
var squareOf = bindSecondArg(Math.pow, 2);
var cubeOf = bindSecondArg(Math.pow, 3);
console.log(squareOf(3)); // 9
console.log(squareOf(4)); // 16
console.log(cubeOf(3));   // 27
console.log(cubeOf(4));   // 64

The ability to create generic functions is very important in functional programming. But there's a clever trick to making this process even more generalized. The bindFirstArg() function itself takes two arguments, the first being a function. If we pass the bindFirstArg function as a function to itself, we can create bindable functions. This can be best described with the following example:

var makePowersOf = bindFirstArg(bindFirstArg, Math.pow);
var powersOfThree = makePowersOf(3);
console.log(powersOfThree(2)); // 9
console.log(powersOfThree(3)); // 27

This is why they're called function factories.

Partial application

Notice that our function factory example's bindFirstArg() and bindSecondArg() functions only work for functions that have exactly two arguments. We could write new ones that work for different numbers of arguments, but that would work away from our model of generalization.

What we need is partial application.

Note

Partial application is the process of binding values to one or more arguments of a function that returns a partially-applied function that accepts the remaining, unbound arguments.

Unlike the bind() function and other built-in methods of the Function object, we'll have to create our own functions for partial application and currying. There are two distinct ways to do this.

  • As a stand-alone function, that is, var partial = function(func){...
  • As a polyfill, that is, Function.prototype.partial = function(){...

Polyfills are used to augment prototypes with new functions and will allow us to call our new functions as methods of the function that we want to partially apply. Just like this: myfunction.partial(arg1, arg2, …);

Partial application from the left

Here's where JavaScript's apply() and call() utilities become useful for us. Let's look at a possible polyfill for the Function object:

Function.prototype.partialApply = function(){
  var func = this; 
  args = Array.prototype.slice.call(arguments);
  return function(){
    return func.apply(this, args.concat(
      Array.prototype.slice.call(arguments)
    ));
  };
};

As you can see, it works by slicing the arguments special variable.

Note

Every function has a special local variable called arguments that is an array-like object of the arguments passed to it. It's technically not an array. Therefore it does not have any of the Array methods such as slice and forEach. That's why we need to use Array's slice.call method to slice the arguments.

And now let's see what happens when we use it in an example. This time, let's get away from the math and go for something a little more useful. We'll create a little application that converts numbers to hexadecimal values.

function nums2hex() {
  function componentToHex(component) {
    var hex = component.toString(16);
    // make sure the return value is 2 digits, i.e. 0c or 12
    if (hex.length == 1) {
      return "0" + hex;
    }
    else {
      return hex;
    }
  }
  return Array.prototype.map.call(arguments, componentToHex).join(''),
}

// the function works on any number of inputs
console.log(nums2hex()); // ''
console.log(nums2hex(100,200)); // '64c8'
console.log(nums2hex(100, 200, 255, 0, 123)); // '64c8ff007b'

// but we can use the partial function to partially apply
// arguments, such as the OUI of a mac address
var myOUI = 123;
var getMacAddress = nums2hex.partialApply(myOUI);
console.log(getMacAddress()); // '7b'
console.log(getMacAddress(100, 200, 2, 123, 66, 0, 1)); // '7b64c8027b420001'

// or we can convert rgb values of red only to hexadecimal
var shadesOfRed = nums2hex.partialApply(255);
console.log(shadesOfRed(123, 0));   // 'ff7b00'
console.log(shadesOfRed(100, 200)); // 'ff64c8'

This example shows that we can partially apply arguments to a generic function and get a new function in return. This first example is left-to-right, which means that we can only partially apply the first, left-most arguments.

Partial application from the right

In order to apply arguments from the right, we can define another polyfill.

Function.prototype.partialApplyRight = function(){
  var func = this; 
  args = Array.prototype.slice.call(arguments);
  return function(){
    return func.apply(
      this,
      [].slice.call(arguments, 0)
      .concat(args));
  };
};

var shadesOfBlue = nums2hex.partialApplyRight(255);
console.log(shadesOfBlue(123, 0));   // '7b00ff'
console.log(shadesOfBlue(100, 200)); // '64c8ff'

var someShadesOfGreen = nums2hex.partialApplyRight(255, 0);
console.log(shadesOfGreen(123));   // '7bff00'
console.log(shadesOfGreen(100));   // '64ff00'

Partial application has allowed us to take a very generic function and extract more specific functions out of it. But the biggest flaw in this method is that the way in which the arguments are passed, as in how many and in what order, can be ambiguous. And ambiguity is never a good thing in programming. There's a better way to do this: currying.

Currying

Currying is the process of transforming a function with many arguments into a function with one argument that returns another function that takes more arguments as needed. Formally, a function with N arguments can be transformed into a function chain of N functions, each with only one argument.

A common question is: what is the difference between partial application and currying? While it's true that partial application returns a value right away and currying only returns another curried function that takes the next argument, the fundamental difference is that currying allows for much better control of how arguments are passed to the function. We'll see just how that's true, but first we need to create function to perform the currying.

Here's our polyfill for adding currying to the Function prototype:

Function.prototype.curry = function (numArgs) {
  var func = this;
  numArgs = numArgs || func.length;

  // recursively acquire the arguments
  function subCurry(prev) {
    return function (arg) {
      var args = prev.concat(arg);
      if (args.length < numArgs) {
        // recursive case: we still need more args
        return subCurry(args);
      }
      else {
        // base case: apply the function
        return func.apply(this, args);
      }
    };
  }
  return subCurry([]);
};

The numArgs argument lets us optionally specify the number of arguments the function being curried needs if it's not explicitly defined.

Let's look at how to use it within our hexadecimal application. We'll write a function that converts RGB values to a hexadecimal string that is appropriate for HTML:

function rgb2hex(r, g, b) {
  // nums2hex is previously defined in this chapter
  return '#' + nums2hex(r) + nums2hex(g) + nums2hex(b);
}
var hexColors = rgb2hex.curry();
console.log(hexColors(11)) // returns a curried function
console.log(hexColors(11,12,123)) // returns a curried function
console.log(hexColors(11)(12)(123)) // returns #0b0c7b
console.log(hexColors(210)(12)(0))  // returns #d20c00

It will return the curried function until all needed arguments are passed in. And they're passed in the same left-to-right order as defined by the function being curried.

But we can step it up a notch and define the more specific functions that we need as follows:

var reds = function(g,b){return hexColors(255)(g)(b)};
var greens = function(r,b){return hexColors(r)(255)(b)};
var blues  = function(r,g){return hexColors(r)(g)(255)};
console.log(reds(11, 12))   // returns #ff0b0c
console.log(greens(11, 12)) // returns #0bff0c
console.log(blues(11, 12))  // returns #0b0cff

So that's a nice way to use currying. But if we just want to curry our nums2hex() function directly, we run into a little bit of trouble. And that's because the function doesn't define any arguments, it just lets you pass as many arguments in as you want. So we have to define the number of arguments. We do that with the optional parameter to the curry function that allows us to set the number of arguments of the function being curried.

var hexs = nums2hex.curry(2);
console.log(hexs(11)(12));     // returns 0b0c
console.log(hexs(11));         // returns function
console.log(hexs(110)(12)(0)); // incorrect

Therefore currying does not work well with functions that accept variable numbers of arguments. For something like that, partial application is preferred.

All of this isn't just for the benefit of function factories and code reuse. Currying and partial application play into a bigger pattern known as composition.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.44.182