The misunderstood functional language

Posted by Daniel on January 04, 2008
Programming

I have always been interested in functional programming languages. The idea of functions as a first-class citizens is extremely powerful. And as a mathematician, I find great beauty in the pure functional languages like Haskell.

You might then imagine my joy years ago when I discovered that JavaScript is actually a functional language in disguise (albeit not a pure one). As a most elementary example, you can have anonymous functions and assign a function to a variable:

var hello = function() { document.write("Hello world"); };
var greeting = hello;
hello();    // prints "Hello world"
greeting(); // prints "Hello world"

But a functional language can do much more interesting things than that. You can pass functions as parameters and functions can return other functions as output. For example, consider the derivative operator:

// returns the derivative of "f" computed numerically.
var Diff = function(f /* function */) {
    return function(x) {
        var h =0.00001;
        return ( f(x+h) - f(x) ) / h;
    };
};

// Test with a cubic function.
var cubic = function(x) { return x*x*x; };

document.write(cubic(4)); // prints 64
document.write("<br/>");
document.write(Diff(cubic)(4)); // prints 48.0001...
document.write("<br/>");
document.write(Diff(Diff(cubic))(4)); // prints 24.0002...

Can your programming language do THAT?

Functional languages have always had fame for being difficult. It is a neat irony that the language used by millions of novices world wide, and the most used language in the world, would turn out to be a functional language.

No comments yet.

Leave a comment

WP_Big_City

xanax 2mg