Does Ruby perform Tail Call Optimization?

后端 未结 5 1126
-上瘾入骨i
-上瘾入骨i 2020-11-28 22:18

Functional languages lead to use of recursion to solve a lot of problems, and therefore many of them perform Tail Call Optimization (TCO). TCO causes calls to a function fro

5条回答
  •  感动是毒
    2020-11-28 22:37

    This builds on Jörg's and Ernest's answers. Basically it depends on implementation.

    I couldn't get Ernest's answer to work on MRI, but it is doable. I found this example that works for MRI 1.9 to 2.1. This should print a very large number. If you don't set TCO option to true, you should get the "stack too deep" error.

    source = <<-SOURCE
    def fact n, acc = 1
      if n.zero?
        acc
      else
        fact n - 1, acc * n
      end
    end
    
    fact 10000
    SOURCE
    
    i_seq = RubyVM::InstructionSequence.new source, nil, nil, nil,
      tailcall_optimization: true, trace_instruction: false
    
    #puts i_seq.disasm
    
    begin
      value = i_seq.eval
    
      p value
    rescue SystemStackError => e
      p e
    end
    

提交回复
热议问题