加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 03:21:14 所属栏目:百科 来源:网络整理
导读:Ruby中的递归函数中是否存在Stack Overflow错误的解决方法? 比方说,我有这个块: def countUpTo(current,final) puts current return nil if current == final countUpTo(current+1,final)end 如果我调用countUpTo(1,10000),我会收到一个错误:堆栈级别太深
Ruby中的递归函数中是否存在Stack Overflow错误的解决方法?

比方说,我有这个块:

def countUpTo(current,final)
    puts current
    return nil if current == final
    countUpTo(current+1,final)
end

如果我调用countUpTo(1,10000),我会收到一个错误:堆栈级别太深(SystemStackError).

它似乎在8187处突破.是否有一些函数我可以调用告诉Ruby忽略堆栈的大小,或者增加最大堆栈大小的方法?

解决方法

如果你正在使用YARV(基于C语言的Ruby 1.9实现),你可以告诉Ruby VM打开尾调用优化:

RubyVM::InstructionSequence.compile_option = {
  :tailcall_optimization => true,:trace_instruction => false
}

def countUpTo(current,final)
end

countUpTo(1,10_000)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读