Writing a Y-Combinator in Ruby 1.9

i’ve read
http://weblog.raganwald.com/2007/02/guest-blogger-tom-moertel-derives-y.html
and finally figured out this:


a trick to make currying easier

class Proc
def -@
self.curry
end
end

def Y &f
g = → h, x, *xs { f[h[h], x, *xs] }
g[g]
end

and had a try:


factorial = Y {|f, n| n == 0 ? 1 : f[n - 1] * n}
puts factorial[12]

=> 479001600

fibbonaci = Y {|f, n| n <= 2 ? 1 : f[n - 1] + f[n - 2]}
puts fibbonaci[10]

=> 55


the intresting part is:
if you replace “x, *xs”(like pattern matching in functional languages
^_^) with “*args”, it overflows the stack.