Writing a Y-Combinator in Ruby 1.9

L

Lui Core

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top