Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Not all recursive algorithms can be translated to an iterative algorithm. Normally only linear algorithms with a single branch can. This means that tree algorithm which have two or more branches and 2d algorithms with more paths are extremely hard to transfer into recursive without using a stack (which is basically cheating).</p> <p>Example:</p> <p>Recursive:</p> <pre><code>listsum: N* -&gt; N listsum(n) == if n=[] then 0 else hd n + listsum(tl n) </code></pre> <p>Iteration:</p> <pre><code>listsum: N* -&gt; N listsum(n) == res = 0; forall i in n do res = res + i return res </code></pre> <p>Recursion:</p> <pre><code>treesum: Tree -&gt; N treesum(t) == if t=nil then 0 else let (left, node, right) = t in treesum(left) + node + treesum(right) </code></pre> <p>Partial iteration (try):</p> <pre><code>treesum: Tree -&gt; N treesum(t) == res = 0 while t&lt;&gt;nil let (left, node, right) = t in res = res + node + treesum(right) t = left return res </code></pre> <p>As you see, there are two paths (left and right). It is possible to turn one of these paths into iteration, but to translate the other into iteration you need to preserve the state which can be done using a stack:</p> <p>Iteration (with stack):</p> <pre><code>treesum: Tree -&gt; N treesum(t) == res = 0 stack.push(t) while not stack.isempty() t = stack.pop() while t&lt;&gt;nil let (left, node, right) = t in stack.pop(right) res = res + node + treesum(right) t = left return res </code></pre> <p>This works, but a recursive algorithm is much easier to understand.</p>
    singulars
    1. This table or related slice is empty.
    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. 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