Anonymous recursion: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added PicoLisp)
(added javascript)
Line 17: Line 17:
Some languages allow you to embed recursion directly in-place. This might work
Some languages allow you to embed recursion directly in-place. This might work
via a label, a local ''gosub'' instruction, or some special keyword.
via a label, a local ''gosub'' instruction, or some special keyword.

Anonymous recursion can also be accomplished using the [[Y combinator]].


If possible, demonstrate this by writing the recursive version of the fibonacci
If possible, demonstrate this by writing the recursive version of the fibonacci
function (see [[Fibonacci sequence]]) which checks for a negative argument
function (see [[Fibonacci sequence]]) which checks for a negative argument
before doing the actual recursion.
before doing the actual recursion.

=={{header|JavaScript}}==
<lang javascript>function fibo(n) {
if (n < 0)
throw "Argument cannot be negative";
else
return (function(x) {
if (n < 2)
return 1;
else
return arguments.callee(n-1) + arguments.callee(n-2);
})(n);
}</lang>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==

Revision as of 19:55, 23 November 2010

Anonymous recursion is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

While implementing a recursive function, it often happens that we must resort to a separate "helper function" to handle the actual recursion.

This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), cause unwanted side-effects, and/or the function doesn't have the right arguments and/and return values.

So we end up inventing some silly name like "foo2" or "foo_helper". I have always found it painful to come up with a proper name, and see a quite some disadvantages:

  • You have to think up a name, which then pollutes the namespace
  • A function is created which is called from nowhere else
  • The program flow in the source code is interrupted

Some languages allow you to embed recursion directly in-place. This might work via a label, a local gosub instruction, or some special keyword.

Anonymous recursion can also be accomplished using the Y combinator.

If possible, demonstrate this by writing the recursive version of the fibonacci function (see Fibonacci sequence) which checks for a negative argument before doing the actual recursion.

JavaScript

<lang javascript>function fibo(n) {

 if (n < 0)
   throw "Argument cannot be negative";
 else
   return (function(x) {
     if (n < 2)
       return 1;
     else
       return arguments.callee(n-1) + arguments.callee(n-2);
   })(n);

}</lang>

PicoLisp

<lang PicoLisp>(de fibo (N)

  (if (lt0 N)
     (quit "Illegal argument" N) )
  (recur (N)
     (if (> 2 N)
        1
        (+ (recurse (dec N)) (recurse (- N 2))) ) ) )</lang>