Tail Call Optimization
Consider the code you write to be a procedure and the generated bytecode that will eventually run to be a process. The factorialIterative() function is an iterative procedure and is compiled into and will run as an iterative process—no surprise there. Likewise, factorialRec() is a recursive procedure and is compiled into, and run as, a recursive process, exactly what we’d expect there as well. However, the real gain, as explained in Structure and Interpretation of Computer Programs [AS96], is when a recursive procedure can be compiled into an iterative process. This approach will bring the best of both worlds—the code can be expressed as recursion, but it can enjoy the runtime behavior of iterations. So, no stack overflow ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access