对于 Ruby 中递归函数中的 Stack Overflow 错误,是否有任何解决方法?
比如说,我有这个 block :
def countUpTo(current, final)
puts current
return nil if current == final
countUpTo(current+1, final)
end
如果我调用 countUpTo(1, 10000)
,我会得到一个错误:stack level too deep (SystemStackError)
。
它似乎在 8187 处中断。有没有我可以调用的函数告诉 Ruby 忽略堆栈的大小,或者增加最大堆栈大小的方法?
最佳答案
如果您正在使用 YARV(Ruby 1.9 的基于 C 的实现),您可以告诉 Ruby VM 打开尾调用优化:
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)
关于ruby - 递归例程中的 "stack level too deep"错误是否有解决方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8732550/