A deep dive into recursion
I've already scratched the surface of recursion in Chapter 3, Basic Functions, showing how the rec
modifier changes the scoping of the function definition. This explicit indication allows the function to reference itself before the function body is fully defined. Now I'll show you how recursion can be employed in the right or wrong way so that you can learn to follow the right recursion pattern.
Tail recursion
I would not be breaking new ground by pointing out that a function, recursive or not, as it is implemented these days, consumes a certain amount of resources for local values, argument values, and so forth. A non-recursive function consumes these resources upon being called and releases them upon returning the result. So far, so good.
But what happens when the function calls itself? Each nested call can stash local resources to be released when this particular level of recursion is done. Hence, a deep recursion may temporarily increase resource consumption....