"... most dismissive report ever produced by a Wall Street analyst" Fortune's Apple-watcher summary of an analysis of Microsoft's plan to launch stores to compete with Apple stores.
JavaScript, Encore:
The function concept and the basic syntax goes back to Fortran, c. 1960. (Born in 1956, Fortran, now structured and object-oriented, is still alive and well where scientists need to do serious number crunching.) In Fortran-descendant C you would write:
function add (num1, num2) {
return num1 + num2;
}
(Actually, it's been a long time since someone wrote an "add" function, but you get the idea.)
That code will run, with only minor changes, through a wide range of compilers and interpreters, including Ruby and JavaScript. Unlike any of the others, here's JavaScript's functional programming alternative:
add = function( num1, num2 ) {
return num1 + num2;
}
With the code in variable "add" you can use "add" like any other variable. For example, you can pass it to another method:
foo = function( bar ) {
return bar(2, 2);
foo( add );
}
"foo" is a function with a parameter named "bar". "bar" is a method that foo will call with the arguments "2" and "2". This is certainly the hard way to get to four, but it has lots of powerful uses. Passing a comparison method to a sort routine, for instance.
This also means that in JavaScript, as in C, you can have an array of functions as easily as an array of strings (and without C's pointer mess). If you've ever needed an array of methods where you can't have one (Java comes to mind) you know how important this is.
Perhaps the best thing about this syntax is its pythonicness. Python itself has this capability but in a messy way with lambda functions. I do hope that the designers of future languages will learn from this innovation. (I doubt it, though. For functional programming you would study Lisp, as Python's designer Guido van Rossum did, and come up with lambda functions.)
No comments:
Post a Comment