How to resolve the algorithm Anonymous recursion step by step in the Elena programming language
How to resolve the algorithm Anonymous recursion step by step in the Elena programming language
Table of Contents
Problem Statement
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), causing unwanted side-effects, and/or the function doesn't have the right arguments and/or 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 some disadvantages: 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.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Anonymous recursion step by step in the Elena programming language
Source code in the elena programming language
import extensions;
fib(n)
{
if (n < 0)
{ InvalidArgumentException.raise() };
^ (n)
{
if (n > 1)
{
^ this self(n - 2) + (this self(n - 1))
}
else
{
^ n
}
}(n)
}
public program()
{
for (int i := -1, i <= 10, i += 1)
{
console.print("fib(",i,")=");
try
{
console.printLine(fib(i))
}
catch(Exception e)
{
console.printLine:"invalid"
}
};
console.readChar()
}
You may also check:How to resolve the algorithm Stirling numbers of the second kind step by step in the zkl programming language
You may also check:How to resolve the algorithm Loops/Do-while step by step in the NewLISP programming language
You may also check:How to resolve the algorithm Twelve statements step by step in the Picat programming language
You may also check:How to resolve the algorithm Sort disjoint sublist step by step in the Tcl programming language
You may also check:How to resolve the algorithm Combinations with repetitions step by step in the Ruby programming language