在递归例程中是否存在“堆栈级太深”错误的解决方法?

Ruby中的递归函数中是否存在Stack Overflow错误的解决方法?

比方说,我有这个块:

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(基于C的Ruby 1.9实现),您可以告诉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) 

您可以重写您的代码段不是递归的:

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

我感谢您的代码可能是您真正想要做的事情的抽象,但如果您想到其他迭代方式而不是递归方式,它可能有助于形成您的解决方案。

HTH

在Ruby 2.0中,您可以使用RUBY_T​​HREAD_VM_STACK_SIZE和其他环境变量指定堆栈大小(以字节为单位)。