Is there a workaround for too deep stack level errors in recursive routines?

Is there a way to work around errors in recursive functions in Ruby?

Say, for example, I have this block:

def countUpTo(current, final)
    puts current
    return nil if current == final
    countUpTo(current+1, final)
end

if I call countUpTo(1, 10000), I get an error message: stack level too deep (SystemStackError).

It seems to break into 8187. Is there some kind of function that I can call saying Ruby to ignore stack sizes or a way to increase the maximum stack size?

+5
source share
3 answers

If you use YARV (an implementation based on C Ruby 1.9), you can say that Ruby VM can optimize call optimization:

RubyVM::InstructionSequence.compile_option = {
  :tailcall_optimization => true,
  :trace_instruction => false
}

def countUpTo(current, final)
    puts current
    return nil if current == final
    countUpTo(current+1, final)
end

countUpTo(1, 10_000)
+2
source

, :

# 'count_up_to' would be a more "Ruby" name ;-)
def countUpTo(current, final)
  (current..final).each { |i| puts i }
end

, , , , , , , .

+2

In Ruby 2.0, you can specify the stack size (in bytes) using RUBY_THREAD_VM_STACK_SIZE and other environment variables.

+2
source

All Articles