Closures and Letrec

Is there a way to create recursive anonymous closures in ruby? For instance
if I write
even = proc {|x| x == 0 ? true : odd(x-1)}
odd = proc {|x| x == 1 ? true : even(x-1)}

In this case even definitely doesn’t know about odd, and actually doesn’t even
know about even. Odd is aware of even though. At least that’s how I have
interpreted how ruby works. We get recursion with full methods, just not with
anonymous procs. Is there any intention for support for this with anonymous
procs? Perhaps though a different syntax? procrec or something?

Charlie

Charles Comstock wrote:

Is there a way to create recursive anonymous closures in ruby? For instance
if I write
even = proc {|x| x == 0 ? true : odd(x-1)}
odd = proc {|x| x == 1 ? true : even(x-1)}

In this case even definitely doesn’t know about odd, and actually doesn’t even
know about even.

Actually, even does know about even because Ruby sees an assignment to
even. To let even know about odd, do this …

odd = nil
even = proc {|x| x == 0 ? true : odd.call(x-1) }
odd = proc {|x| x == 0 ? false : even.call(x-1)}

By assigning to odd, ruby now knows that “odd” is a variable, not a
method name. (Notice I changed the definition of odd to avoid infinite
recursion for the false case.)

···


– Jim Weirich jweirich@one.net http://onestepback.org

“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)