Hi there! Topic of the day: functional programming for the programmer who comes from a non-functional background. About two years ago, I began working at a company which used a Scheme dialect (JazzScheme) as its main software development language. At the time I had virtually no experience with functional programming and Scheme seemed quite alien-like from an aesthetic point of view. In order to learn the language, I dived into Structure and Interpretation of Computer Programs. I clearly remember having an 'epiphany' in the corner of a coffee shop, revolving around the fact that you could use a function as an actual data type. This was completely foreign to me, having worked primarily with Java and PHP up until that point, and blew my mind.

Javascript has been shining in the spotlight recently, backed by HTML5, with new tools and frameworks emerging every day. I am not planning on preaching that you should always program in a purely functional sense. However I do believe that introducing yourself to the functional paradigm can better you as a programmer, or at the very least offer you a new perspective. I will not try to define the functional programming paradigm as this topic can cause length debates, so I will focus on the ability to use functions as a variable for this case. The reason I offer Javascript as a gentle introduction is that it is much more relatable for a programmer who is used to a C-style syntax language, as opposed to the unique syntax of LISP dialects.

The following lines, which are perfectly valid Javascript, are a great place to start:

1
2
3
4
5
var aFunction = function(){
    console.log('Hello, world!');
};

aFunction();

What is going on here? Essentially, the right hand side of the assignment is creating an anonymous function (that is, it has no name at its moment of creation), and then assigning it as the value of aFunction. We then execute the variable, and we see an infamous message in our console! This snippet is one of the keys to understanding the meaning of functions as first class citizens. Now if we can assign it to one variable that means the following code is also perfectly valid:

1
2
3
4
5
6
7
var aFunction = function(){
    console.log('Hello, world!');
};

var bFunction = aFunction;

bFunction();

Of course, all these functions are valid Javascript functions, so therefore we can also give a function arguments, like so:

1
2
3
4
5
6
var adder = function(a, b){
    return a + b;
}

console.log(adder(1,2));
console.log(adder(5,6));

As you can see, we now have the ability to pass around functions as if they were simple variables (and in reality, they are simple variables!). The power of this truly shines in the fact that since they are variables, we can pass them to functions. Functional programming is based on the idea that with it we make many small functions, and combine them to make powerful code. There are many standard patterns in functional programming, but to begin with I will show you one which can be extremely practical in Javascript - passing functions as callbacks. Suppose you repeatedly find yourself testing things, and then either showing a success message or executing some failure code. We could make a function which would automate this for us, simplifying our life:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
var test(testFunction, successFunction, failFunction){
    if (testFunction()){
        successFunction();
    } else {
        failFunction();
    }
}

var testFunction = function(){ return 2 == 2; },
    successFunction = function(){ console.log('This machine is awesome!'); },
    failFunction = function(){ console.log('Uh oh!'); };

test(testFunction, successFunction, failFunction);

I will now show you to rather popular functional programming standards, a forEach and a map. The forEach pattern gets passed an array and a function, and executes the function with each element of the array. The map function gets passed an array and a function, and returns an array of the result of the function for each element. Here are some basic examples:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
var forEach = function(valueArray, eachFunction){
    for (var i = 0, l = valueArray.length; i < l; i++){
        eachFunction(valueArray[i]);
    }
}

var map = function(valueArray, mapFunction){
    var returnArray = [];
    for (var i = 0, l = valueArray.length; i < l; i++){
        returnArray.push(mapFunction(valueArray[i]));
    }
    return returnArray;
}

These two functions allow us to re-use these patterns (which occur more often than you'd think) and we can combine them easily. Suppose we want to have a method which uses forEach to print out each element of an array, and we have a map method which squares every element of an array, we can do something like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
var logger = function(element){
    console.log('Logger - ' + element);
}

var square = function(element){
    return element * element;
}

var values = [1,2,3,4,5,6,7];

forEach(values, logger); // Will print each value.
forEach(map(values, square), logger); // Will print out the square of each value. 
forEach(map(map(values, square), square), logger); // Will print out the 4th power.

So now that we know how a forEach and a map is implemented, I will gladly let you in on the following: the Array prototype already has a forEach and a map method! Using them is as simple as:

1
2
3
4
5
6
7
8
9
// Print out all elements of an array
[1,2,3].forEach(function(item){
    console.log(item);
});

// Square each element of an array
var squared = [1,2,3].map(function(item){
    return item * item;
});

The last thing I will be showing you today will be using what you have learned so far to create function factories - functions which return functions. Suppose you want to create a general function which creates helper functions for binding a callback to a given element's event handler, and you want it to be compatible across different browsers. We can generalize this into a function which we will pass the element and event to, and it will return us a function allowing us to attach an event handler to that element.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
var getEventBinder = function(element, event){
    var func;

    // We are checking for IE event binding style, and then
    // building a function which accepts a callback and
    // binds it to the appropriate event.
    if (element.attachEvent) {
        func = function(callback){
            element.attachEvent('on' + event, callback);
        };
    } else {
        func = function(callback){
            element.addEventListener(event, callback, true);
        }
    }

    return func;
}

// We can now use this to get a function allowing us to
// bind a callback to the click handler of a div.
var div = document.getElementById('someSpecialDiv');

var divClickAttacher = getEventBinder(div, 'click');

divClickAttacher(function(){
    alert("The div was clicked!");
});

What are we doing here? We are creating a function which accepts an element and the name of an event, determines whether we are using IE event binding style (attachEvent) or not (addEventListener), and finally returns a function which accepts a callback and is crafted to bind this callback to the event and element we had passed. Admittedly this is using a little bit of closure magic, but hopefully the example is still clear. If not, I will find some good references for explaining closures, as I've seen this done many, many times and fear I could not compete.

I think for today we will leave it at that. This is only scratching the surface of the power of functional programming, but hopefully I have opened your mind to a different style of programming. If you have any questions or comments feel free to post!

Thanks for reading, Dominic.