LoginSignup
21
19

More than 5 years have passed since last update.

Ruby で無名 lambda 再帰

Posted at

ラムダ式を再帰させたいと思ったことは誰にでもあると思います。

そんな時、以下のような Proc オブジェクト拡張を行います。

class Proc
  def self_curry
    self.curry.call(self)
  end
end

すると、lambda のオブジェクトに sef_curry メソッドが追加されるので、xの階乗を求める無名関数は以下のように書けます。

lambda{|f,x| x == 1 ? 1 : x * f.call(f, x-1) }.self_curry.call(5)
 => 120

すばらしい。

第一引数として「自分自身」を受け取る無名関数となっているのがポイントです。

self_curry の呼び出しによって python のメソッドっぽく自分自身が第一引数にバインドされるようになります。

21
19
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
21
19