実装
coffeeならなんと一行です。
Function::curry = (args1...) -> (args2...) => @apply @, args1.concat args2
apply黒魔術最高!(黒って言う程でもないけど)
※ prototype拡張してるので信条に反する人は注意
JSならこうなる(↑をコンパイルしただけ)
Function.prototype.curry = function() {
var args1,
_this = this;
args1 = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return function() {
var args2;
args2 = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return _this.apply(_this, args1.concat(args2));
};
};
使い方
Function::curry = (args1...) -> (args2...) => @apply @, args.concat args2
add3val = (x, y, z) -> x + y + z
f1 = add3val.curry(1)(2, 3)
f2 = add3val.curry(1, 2)(3)
f3 = add3val.curry(1, 2, 3)()
console.log f1, f2, f3 #=> 6 6 6
これでより関数型っぽくなりましたね、必要かどうかはともかく
注意点として、カリー化した関数はその時点での参照を保持しているので、ちゃんとdeleteしないとメモリが漏れます。