There's more...
The interesting thing about this solution is that it uses an internal function that does the recursion. The result of the recursion is stored as an argument. When a special case is hit (such as the list being empty in our example), the result of the recursion is returned.
The recursion is tail recursion. It means that whenever we recurse, we ensure that the last function that is evaluated is exactly the same function that we are defining. In our example, we always called reverse' function as a top expression. The compiler optimizes the tail recursive functions such that they are executed in constant space and without adding them to stack.
The following diagram shows how a tail recursive function works. The diagram shows how ...
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