Get Proc of current block?

I

Intransition

Is there any way to get a hold of the current block? I've been playing
around with recursive enumerations and it occurs to me that the most
flexible technique would simply be to reuse the currently running
block.

For example, where `this` would be the current block:

h = {:a=>1, :b=>{:c=>3}}

h.map{ |k,v| Hash===v ? [k.to_s, v.map(&this)] : [k.to_s,v.to_s] }

#=> {"a"=>"1", "b"=>{"c"=>"3"}}
 
M

Michael Fellinger

Is there any way to get a hold of the current block? I've been playing
around with recursive enumerations and it occurs to me that the most
flexible technique would simply be to reuse the currently running
block.

For example, where `this` would be the current block:

=C2=A0h =3D {:a=3D>1, :b=3D>{:c=3D>3}}

=C2=A0h.map{ |k,v| Hash=3D=3D=3Dv ? [k.to_s, v.map(&this)] : [k.to_s,v.to= _s] }

=C2=A0#=3D> {"a"=3D>"1", "b"=3D>{"c"=3D>"3"}}

That's called the Y-combinator, something i wish could be added to
core, but would be afraid of the many nay-sayers who are already
confused by the current number of ways of creating blocks :)

def y(*args, &block)
y =3D lambda{|*args| block.(*args, &y) }
end

p y{|n, acc, &b|
n < 2 ? acc : b.(n-1, n * acc)
}.(5, 1)



--=20
Michael Fellinger
CTO, The Rubyists, LLC
 
J

John Barnette

Is there any way to get a hold of the current block? I've been playing
around with recursive enumerations and it occurs to me that the most
flexible technique would simply be to reuse the currently running
block.

Limited, and pure evil:

lambda { |x| p x +=3D 1; redo }[0]

Infinitely increments. `redo` lets you restart the current block, but =
you must manipulate the original args instead of passing 'em. Don't do =
this. :)


~ j.
 
I

Intransition

That's called the Y-combinator, something i wish could be added to
core, but would be afraid of the many nay-sayers who are already
confused by the current number of ways of creating blocks :)

def y(*args, &block)
=A0 y =3D lambda{|*args| block.(*args, &y) }
end

p y{|n, acc, &b|
=A0 n < 2 ? acc : b.(n-1, n * acc)

}.(5, 1)

Helpful. Thanks. I am considering adding to Facets, but it would have
to be called #Y b/c YAML defines #y.
 

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

No members online now.

Forum statistics

Threads
474,145
Messages
2,570,825
Members
47,371
Latest member
Brkaa

Latest Threads

Top