How To Keep a Block on a Recursive Function

F

fluffyx

Hi. I have a recursive function (it calls itself) that accepts a block.

def arecursor(param)
[...]
yield var
[...]
if (some condition)
arecursor(another_var)
end
[...]
end

When the function is first called, the yield statement succeeds. But
after the function calls itself, it looses the block. How do I make the
block persistant-- can I do something like this::?

arecursor(another_var) { use my block }

Thanks,
Oliver
 
T

Trans

You can make the block a normal parameter using the & operator.

def arecursor(param, &block)
[...]
block.call(var)
[...]
if (some condition)
arecursor(another_var,&block)
end
[...]
end

T.
 
J

Joel VanderWerf

Trans said:
You can make the block a normal parameter using the & operator.

def arecursor(param, &block)
[...]
block.call(var)
[...]
if (some condition)
arecursor(another_var,&block)
end
[...]
end

T.

You can also do it with yield, but it doesn't improve performance.
(Using yield instead of & is faster in some cases, because no Proc
object is created.)

def recurse_n_times_using_yield(n)
return if n == 0
yield n
recurse_n_times_using_yield(n-1) do |nn|
yield nn
end
end

recurse_n_times_using_yield(10) {|n| p n}

def recurse_n_times_using_proc(n, &block)
return if n == 0
yield n
recurse_n_times_using_yield(n-1, &block)
end

recurse_n_times_using_proc(10) {|n| p n}


require 'benchmark'

Benchmark.bmbm do |bm|
bm.report 'using_yield' do
recurse_n_times_using_yield(1000) {|n|}
end
bm.report 'using_proc' do
recurse_n_times_using_proc(1000) {|n|}
end
end

__END__


Rehearsal -----------------------------------------------
using_yield 1.760000 0.010000 1.770000 ( 1.775127)
using_proc 0.610000 0.000000 0.610000 ( 0.612273)
-------------------------------------- total: 2.380000sec

user system total real
using_yield 0.620000 0.000000 0.620000 ( 0.621149)
using_proc 0.620000 0.000000 0.620000 ( 0.618183)
 

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
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top