Search code examples
rubyrecursionstack-overflowtail-call-optimization

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


Is there any workaround for Stack Overflow 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: stack level too deep (SystemStackError).

It appears to break at 8187. Is there some function that I can call telling Ruby to ignore the size of stacks, or a way to increase the maximum stack size?


Solution

  • If you're using YARV (the C based implementation of Ruby 1.9), you can tell the Ruby VM to turn tail call optimization on:

    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)