Thursday 14 November 2013

Functional Programming and You

Let me blow your mind real quick.

The kind of programming I've learned through high school has always been imperative, procedural, and/or object-oriented. In other words, most of the time I told the compiler exactly what I want, like

for (int i; i < arr.length; i++) {
    arr[i].doThisThing("Not sure what language this is written in");
}

This has taught me a lot about logical thinking and low-level computer architecture, but is really clunky - I mean I gotta access each item by its index, and then do some laundry list of tasks.

Enter Javascript* stage left


Writing Javascript introduced me to functional programming - kind of out of necessity, since procedural-style Javascript sucks so bad. The damn language can't even run for object in list on an array without doing something weird! But look at this:

forEach( some_array, function (each_object) {
    each_object.doThisThing("OMG YOU GUYS LOOK");
});

Did you see that? We just passed each element of the array to a function and operated directly on them, without indices! Sure, you say, Python and Java can do that to with their for-each constructs. But what if I do this**?***

linear = [1, 2, 3, 4];
squares = map( linear, function (val) {
    return (val * val);
});

squares == [1, 4, 9, 16];    // True
linear == [1, 2, 3, 4];   //True

Using the same functional style as before, we generated a new array from the previous one without specifically manipulating each value (imagine the tedium of doing that with indices)! Here's another:

evens = filter( [1, 2, 3, 4], function (val) {
    return (val % 2 == 0);    //True if even
});

evens == [2, 4];

An even nicer way to do it is to use first-class functions and define an is_even function separately:

is_even = function (val) {
   return (val % 2 == 0);
}
evens = filter( [1, 2, 3, 4], is_even);
more_evens = filter( [5, 6, 7, 8], is_even);

Did we just pass a function as an argument?! Yeah! Wowwowow! That's what first-class functions means, and usually goes hand-in-hand with functional programming. This stuff was first used in Scheme (a strict version of Lisp), but nobody used that. Good thing Javascript took up the cause.

And that's it! Hope you learned something. Happy_cat.gif



* I know Javascript isn't much of a functional language, but that's where I started to pick it up. It is very extensible however, with libraries like wu.js and underscore.js providing some functional power.

** Technically the map() function isn't global in Javascript, but you could use the underscore.js version the same way.

*** Sorry for clobbering the global namespace, I didn't want to cause confusion around the var statement.

No comments:

Post a Comment