12
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScriptでカリー化関数を作る

Last updated at Posted at 2013-03-09

実装

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しないとメモリが漏れます。

12
13
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
12
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?