Anonymous recursion: Difference between revisions
Content added Content deleted
Not a robot (talk | contribs) (Add APL) |
(Added Quackery.) |
||
Line 2,310: | Line 2,310: | ||
(A A N))) |
(A A N))) |
||
</lang> |
</lang> |
||
=={{header|Quackery}}== |
|||
Quackery can do anonymous recursion via the word <code>recurse</code>. |
|||
<pre>[ dup 0 < iff |
|||
$ "negative argument passed to fibonacci" |
|||
fail |
|||
[ dup 2 < if done |
|||
dup 1 - recurse |
|||
swap 2 - recurse + ] ] is fibonacci ( n --> n )</pre> |
|||
<code>recurse</code> causes the current nest (i.e. the on that starts <code>[ dup</code> and ends <code>+ ]</code> to be evaluated recursively. This means that if, for example, the first recursive call was inside one or more nested nests, it would not work as desired. So the first instance of <code>recurse</code> in: |
|||
<pre>( *** faulty code *** ) |
|||
[ dup 0 < iff |
|||
$ "negative argument passed to fibonacci" |
|||
fail |
|||
[ dup 2 < if done |
|||
[ [ [ [ [ [ |
|||
[ dup 1 - recurse ] |
|||
] ] ] ] ] ] |
|||
swap 2 - recurse + ] ] is fibonacci ( n --> n )</pre> |
|||
would cause the nest <code>[ dup 1 - recurse ]</code>to be evaluated, and the program would go into a tailspin, recursively evaluating that nest until the return stack overflowed. |
|||
This limitation can be overcome with the understanding that recursion can be factored out into two ideas, i.e. self=reference and evaluation. The self-reference word in Quackery is <code>this</code>, which puts a pointer to the current nest on the data stack (usually just called "the stack") and the evaluation word is <code>do</code>, which takes a pointer from the stack and evaluates it. So <code>this do</code> is equivalent to <code>recurse</code>. |
|||
The final example fixes the previous example by putting <code>this</code> at the correct level of nesting and evaluating it within the nested nests with <code>do</code>. |
|||
<pre>[ dup 0 < iff |
|||
$ "negative argument passed to fibonacci" |
|||
fail |
|||
[ dup 2 < if done |
|||
this |
|||
[ [ [ [ [ [ |
|||
[ dip [ dup 1 - ] do ] |
|||
] ] ] ] ] ] |
|||
swap 2 - recurse + ] ] is fibonacci ( n --> n ) |
|||
</pre> |
|||
Quackery also provides named recursion with <code>forward</code> and <code>resolves</code>, so this is usually not ''necessary'' but can be useful in unusual circumstances. |
|||
=={{header|R}}== |
=={{header|R}}== |