LoginSignup
6
4

More than 5 years have passed since last update.

JSでデフォルトカリー化

Last updated at Posted at 2016-11-15

JS(ES2015)でデフォルトカリー化を味わうためには、関数定義は以下のようにするものだ、と自分に言いきかせます。

func = arg1 => arg2 => .. 関数本体

たとえば、以下のように関数を定義して…

func = x => y => z => x+y+z;

呼び出しは以下のようにします。

console.log(func(3)(4)(5)); // ==> 12

これでOK。
え?呼び出しが煩雑だって?
ならば、以下のように$プロパティをFunctionに定義すると…

uncurry = (func) => {
    return new Proxy(func,
                     {
                         apply(target, thisArg, argsList) {
                             return argsList.reduce((last, arg)=>{
                                 return last.call(thisArg, arg);
                             }, target);
                         }
                     }
                    );
};


Object.defineProperty(Function.prototype, "$", {
    get: function() {return uncurry(this); },
});

こんな風にできます。

console.log(func.$(3,4,5)); // ==> 12 
console.log(func(3).$(4,5)); // ==> 12 
console.log(func(3)(4).$(5)); // ==> 12 
console.log(func.$(3,4)(5)); // ==> 12

$はhaskellの$のイメージ。

追記

NPMパッケージ化しました。

6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4