Skip to content

Instantly share code, notes, and snippets.

@slimane
Last active August 29, 2015 14:01
Show Gist options
  • Save slimane/aa8587bf5c814b23f5b6 to your computer and use it in GitHub Desktop.
Save slimane/aa8587bf5c814b23f5b6 to your computer and use it in GitHub Desktop.
SICPのexcrise1.2をjavascriptで書いた
// Exercise1.2
var calc = function(f){
return function(){
var tmp;
for (var i = 0; i < arguments.length; i++){
var num = arguments[i];
if (typeof tmp === 'undefined'){
tmp = num;
}else{
tmp = f(tmp, num);
}
}
return tmp;
}};
var add = calc(function(x, y){ return x + y;});
var mul = calc(function(x, y){ return x * y;});
var div = calc(function(x, y){ return x / y;});
var sub = calc(function(x, y){ return x - y;});
console.log(add(5, 4, 3, 2, 1)); // 15
console.log(mul(5, 4, 3, 2, 1)); // 15
console.log(sub(5, 4, 3, 2, 1)); // -5
console.log(div(5, 4, 3, 2, 1)); // 0.20833..4
var ext1_2 = function(){
return div(add(5, 4, sub(2
, sub(3
, add(6, div(4, 5)))))
, calc(mul)(3
, sub(6, 2)
, sub(2, 7)));
};
console.log('EXT1.2 : ' + ext1_2());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment