堆栈级别太深,即使递归调用是在函数结束?

时间:2016-11-25 03:10:15

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

我遵循答案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中删除了以下内容并且它有效吗?

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

1 个答案:

答案 0 :(得分:0)

您需要为递归函数调用设置某种终止条件。您已将该条件设为unless next_token.nil?,但是当您尝试终止时,您确定next_token变为零,可能只需要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