【问题标题】:Stack level too deep, even though recursive call is at end of function?堆栈级别太深,即使递归调用在函数末尾?
【发布时间】:2017-04-09 09:24:28
【问题描述】:

我正在遵循答案here 的建议,并已确认 :tailcall_optimization=>true 和 :trace_instruction=>false,但我仍然得到:

SystemStackError: 堆栈级别太深

...

...8696 级...

我做错了什么?

  def persist_shipments_then_next(prev_data)
    persist_shipments(prev_data)

    next_token = prev_data['NextToken']
    puts next_token
    unless next_token.nil?
      next_data = @client.list_inbound_shipments_by_next_token(
        next_token
      ).parse

      persist_shipments_then_next(next_data)
    end
  end

更新:我从 application.rb 中删除了以下内容并且它可以工作 WTF?:

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

【问题讨论】:

标签: ruby-on-rails ruby recursion pagination tail-recursion


【解决方案1】:

递归函数调用需要某种终止条件。您已将该条件设置为unless next_token.nil?,但您确定next_token 在您尝试终止时变为nil,可能您只需要执行unless next_token

def persist_shipments_then_next(prev_data)
  persist_shipments(prev_data)

  next_token = prev_data['NextToken']
  unless next_token
    next_data = @client.list_inbound_shipments_by_next_token(
      next_token
    ).parse

    persist_shipments_then_next(next_data)
  end
end

【讨论】:

  • 一旦没有更多数据要检索,NextToken 将从prev_data 中消失。我已经在 Rails 控制台中手动确认了这一点。
猜你喜欢
  • 2015-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-04
  • 2013-10-05
  • 2011-11-17
  • 2012-07-24
  • 2016-08-02
相关资源
最近更新 更多