From: Jim Weirich Date: 2003-02-04T14:27:13+09:00 Subject: Re: Local variables & blocks On Mon, 2003-02-03 at 17:46, Brian Candler wrote: > I can't see how to get a Proc object to refer to itself except by passing a > reference to itself as one of its arguments, That's exactly how its done. The trick is to removed the "me" variable from the argument list by embedding the recursive function inside another proc that binds "me". Something like this ... proc do |me| proc do |acc,count| #... end end Then all you have to get "me" bound to the right proc instance. The result is call a Y combinator, for reasons I don't fully understand. I'm always at the brink of understanding the Y combinator, but never fully "get it". It is fun to play with however. Here's a ruby version of Y. http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/20469 And for those who really wish to torture themselves, here it is in Java. http://www.clug.org//ml/archive/programming/1998-11/msg00014.html And if you are interested in the machanics of Y, here it is again in scheme (where I first learned it) along with some discussion on how to build it ... http://www.clug.org//ml/archive/programming/1998-11/msg00028.html As a final thought along the recreational uses of "proc", I leave you with the following code inspired by the thread on block and local variables. def weird x = nil [proc {x}, proc {|x|}] end What does it do? Hint: This works in the current version of Ruby, but it will fail when/if Matz ever implements the new rules for blocks and local scope. -- -- Jim Weirich jweirich@one.net http://w3.one.net/~jweirich --------------------------------------------------------------------- "Beware of bugs in the above code; I have only proved it correct, not tried it." -- Donald Knuth (in a memo to Peter van Emde Boas)