How To Keep a Block on a Recursive Function

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

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.

Trans wrote:

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)

···

--
      vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407