Tail call optimisation (TCO)

avoid allocating a new stack frame for a function because the calling function will simply return the value that it gets from the called function. The most common use is tail-recursion, where a recursive function written to take advantage of tail-call optimization can use constant stack space. - SO

TCO transformation

Fibonacci

def fibo(n, a, b)
	 (n > 0) ? fibo(n - 1, b, a + b) : a;       
end

Ruby Tail Call Optimization?

The Ruby Language Specification doesn’t say anything about TCO. It doesn’t say you have to do it, but it also doesn’t say you can’t do it.

  • This is unlike Scheme, where the Language Specification requires that all Implementations must perform TCO.

  • But it is also unlike Python, where Guido van Rossum has made it very clear on multiple occasions (the last time just a couple of days ago) that Python Implementations should not perform TCO.

Tail Calls in C

Written on June 29, 2019, Last update on April 25, 2021
optimize recurse algorithm ruby Fibonacci