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

南楼画角 提交于 2019-12-04 07:55:11
Andrew Grimm

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)

You can rewrite your snippet not to be recursive:

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

I appreciate your code is probably an abstraction of what you're really trying to do, but it might help to form your solution if you think of other ways to iterate rather than recursively.

HTH

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!