Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Consider a simple function that adds the first N integers. (e.g. <code>sum(5) = 1 + 2 + 3 + 4 + 5 = 15</code>).</p> <p>Here is a simple JavaScript implementation that uses recursion:</p> <pre class="lang-js prettyprint-override"><code>function recsum(x) { if (x===1) { return x; } else { return x + recsum(x-1); } } </code></pre> <p>If you called <code>recsum(5)</code>, this is what the JavaScript interpreter would evaluate:</p> <pre class="lang-js prettyprint-override"><code>recsum(5) 5 + recsum(4) 5 + (4 + recsum(3)) 5 + (4 + (3 + recsum(2))) 5 + (4 + (3 + (2 + recsum(1)))) 5 + (4 + (3 + (2 + 1))) 15 </code></pre> <p>Note how every recursive call has to complete before the JavaScript interpreter begins to actually do the work of calculating the sum.</p> <p>Here's a tail-recursive version of the same function:</p> <pre class="lang-js prettyprint-override"><code>function tailrecsum(x, running_total=0) { if (x===0) { return running_total; } else { return tailrecsum(x-1, running_total+x); } } </code></pre> <p>Here's the sequence of events that would occur if you called <code>tailrecsum(5)</code>, (which would effectively be <code>tailrecsum(5, 0)</code>, because of the default second argument).</p> <pre class="lang-js prettyprint-override"><code>tailrecsum(5, 0) tailrecsum(4, 5) tailrecsum(3, 9) tailrecsum(2, 12) tailrecsum(1, 14) tailrecsum(0, 15) 15 </code></pre> <p>In the tail-recursive case, with each evaluation of the recursive call, the <code>running_total</code> is updated.</p> <p><em>Note: The original answer used examples from Python. These have been changed to JavaScript, since modern JavaScript interpreters support <a href="https://stackoverflow.com/questions/310974/what-is-tail-call-optimization">tail call optimization</a> but Python interpreters don't.</em></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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