是否有解决“堆栈级别太深"的方法?递归例程中的错误? [英] Is there a workaround for "stack level too deep" errors in recursive routines?
本文介绍了是否有解决“堆栈级别太深"的方法?递归例程中的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有解决 Ruby 递归函数中堆栈溢出错误的解决方法?
Is there any workaround for Stack Overflow errors in recursive functions in Ruby?
比如说,我有这个块:
def countUpTo(current, final)
puts current
return nil if current == final
countUpTo(current+1, final)
end
如果我调用 countUpTo(1, 10000)
,我得到一个错误:stack level too deep (SystemStackError)
.
if I call countUpTo(1, 10000)
, I get an error: stack level too deep (SystemStackError)
.
它似乎在 8187 处中断.有没有我可以调用的函数告诉 Ruby 忽略堆栈的大小,或者有什么方法可以增加最大堆栈大小?
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?
推荐答案
如果您使用 YARV(Ruby 1.9 的基于 C 的实现),您可以告诉 Ruby VM 打开尾调用优化:
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)
这篇关于是否有解决“堆栈级别太深"的方法?递归例程中的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文