Tail recursion
suggest changeMany recursive algorithms can be expressed using iteration. For instance, the greatest common divisor function can be written recursively:
def gcd(x, y)
return x if y == 0
return gcd(y, x%y)
end
or iteratively:
def gcd_iter(x, y)
while y != 0 do
x, y = y, x%y
end
return x
end
The two algorithms are equivalent in theory, but the recursive version risks a SystemStackError. However, since the recursive method ends with a call to itself, it could be optimized to avoid a stack overflow. Another way to put it: the recursive algorithm can result in the same machine code as the iterative if the compiler knows to look for the recursive method call at the end of the method. Ruby doesn’t do tail call optimization by default, but you can turn it on with:
RubyVM::InstructionSequence.compile_option = {
tailcall_optimization: true,
trace_instruction: false
}
In addition to turning on tail-call optimization, you also need to turn off instruction tracing. Unfortunately, these options only apply at compile time, so you either need to require the recursive method from another file or eval the method definition:
RubyVM::InstructionSequence.new(<<-EOF).eval
def me_myself_and_i
me_myself_and_i
end
EOF
me_myself_and_i # Infinite loop, not stack overflow
Finally, the tail call must be the entire expression that is returned. That means you need to rewrite the standard factorial function:
def fact(x)
return 1 if x <= 1
return x*fact(x-1)
end
To something like:
def fact(x, acc=1)
return acc if x <= 1
return fact(x-1, x*acc)
end
This version passes the accumulated product via a second (optional) argument that defaults to 1.
Further reading: Tail Call Optimization in Ruby and Tailin’ Ruby.