Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In general, a directly tail recursive function (i.e., one that always calls itself directly and cannot be overridden) will always be optimized into a <code>while</code> loop by the compiler. You can use the <code>@tailrec</code> annotation to verify that the compiler is able to do this for a particular function.</p> <p>As a general rule, any tail recursive function can be rewritten (usually automatically by the compiler) as a <code>while</code> loop <em>and vice versa</em>.</p> <p>The purpose of writing functions in a (tail) recursive style is not to maximize performance or even conciseness, but to make the intent of the code as clear as possible, while simultaneously minimizing the chance of introducing bugs (by eliminating mutable variables, which generally make it harder to keep track of what the "inputs" and "outputs" of the function are). A properly written recursive function consists of a series of checks for terminating conditions (using either cascading <code>if</code>-<code>else</code> or a pattern match) with the recursive call(s) (plural only if not tail recursive) made if none of the terminating conditions are met. </p> <p>The benefit of using recursion is most dramatic when there are several different possible terminating conditions. A series of <code>if</code> conditionals or patterns is generally much easier to comprehend than a single <code>while</code> condition with a whole bunch of (potentially complex and inter-related) boolean expressions <code>&amp;&amp;</code>'d together, especially if the return value needs to be different depending on which terminating condition is met.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload