Asp Forum
Home
|
Login
|
Register
|
Search
Forums
>
comp.lang.ruby
Writing a Y-Combinator in Ruby 1.9
Lui Core
6/10/2009 2:07:00 AM
i've read
http://weblog.raganwald.com/2007/02/guest-blogger-tom-moertel-deri...
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.
--
Posted via
http://www.ruby-...
.
Servizio di avviso nuovi messaggi
Ricevi direttamente nella tua mail i nuovi messaggi per
Writing a Y-Combinator in Ruby 1.9
Inserendo la tua e-mail nella casella sotto, riceverai un avviso tramite posta elettronica ogni volta che il motore di ricerca troverà un nuovo messaggio per te
Il servizio è completamente GRATUITO!
x
Login to ForumsZone
Login with Google
Login with E-Mail & Password