How to resolve the algorithm Anonymous recursion step by step in the Prolog programming language
How to resolve the algorithm Anonymous recursion step by step in the Prolog 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 Prolog programming language
Source code in the prolog programming language
:- use_module(lambda).
fib(N, _F) :-
N < 0, !,
write('fib is undefined for negative numbers.'), nl.
fib(N, F) :-
% code of Fibonacci
PF = \Nb^R^Rr1^(Nb < 2 ->
R = Nb
;
N1 is Nb - 1,
N2 is Nb - 2,
call(Rr1,N1,R1,Rr1),
call(Rr1,N2,R2,Rr1),
R is R1 + R2
),
% The Y combinator.
Pred = PF +\Nb2^F2^call(PF,Nb2,F2,PF),
call(Pred,N,F).
You may also check:How to resolve the algorithm First-class functions/Use numbers analogously step by step in the Phix programming language
You may also check:How to resolve the algorithm Damm algorithm step by step in the Julia programming language
You may also check:How to resolve the algorithm A+B step by step in the Scratch programming language
You may also check:How to resolve the algorithm User input/Text step by step in the Liberty BASIC programming language
You may also check:How to resolve the algorithm CUSIP step by step in the Ada programming language