|
Okay, sure, let's look at it in Javascript. The task? Take a list of numbers, and produce a list containing only the squares of those numbers--and only those squares falling between 10 and 50. var inList = [1,2,3,4,5,6,7,8,9,10];
var non_fp = function ( myListOfNumbers ) {
var out = [];
var temp = [];
var i = 0;
var j = 0;
// square the numbers
for (i = 0; i < myListOfNumbers.length; i++) {
temp.push( myListOfNumbers[i] * myListOfNumbers[i] );
}
for (j = 0; j < temp.length; j++) {
if ( temp[j] > 10 && temp[j] < 100 ) {
out.push( temp[j] );
}
}
return out;
}
var fp = function ( myListOfNumbers ) {
return myListOfNumbers.map( function (x) { return x*x; } )
.filter( function (x) { return (x > 10) && (x< 100); });
}
The first has no side effects.The second version has no side effects, and wouldn't be possible without first-class functions, and to me is clearly the more functional answer. |