4

The following is my sample code:

def test(v)
  test(v-1) if v > 0
  p v
end

if i call test(11893) it is working fine. if i have v > 11893, it is throwing SystemStackError. How to increase the limit for this error?

Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
lokanadham100
  • 1,149
  • 1
  • 11
  • 22

1 Answers1

6

MRI has tail recursion optimization switched off by default. But one might turn it on:

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

also, the code itself must use tail recursion:

def test(v)
  return unless v > 0
  p v
  test(v-1) 
end
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
  • Do you know if there's a particular reason why it's off by default? – Aaron Christiansen Apr 08 '18 at 09:58
  • 1
    @AaronChristiansen nope, unfortunately I have no idea. The wild guess would be: either it’s still experimental or “ruby is not about recursion.” – Aleksei Matiushkin Apr 08 '18 at 10:18
  • 1
    The [turn it on](http://nithinbekal.com/posts/ruby-tco/) link contains a short section, "A negative side to TCO?" which contains, "Guido van Rossum wrote about why he is against supporting TCO in Python. One major problem he points out is that TCO messes up the stack traces, and therefore makes debugging harder.". That is followed by "...Matz is less opposed to the idea...Ruby allows you to optionally enable it...". – Cary Swoveland Apr 08 '18 at 17:43