I wrote a predicate fib/2 to calculate the Fibonacci numbers in Prolog. Though it works, it always says "out of local stack" and the error looks like:
?- fib(10, F).
F = 55 ;
ERROR: Out of local stack
my predicate is below:
fib(0, 0).
fib(1, 1).
fib(N, NF) :-
A is N - 1,
B is N - 2,
fib(A, AF),
fib(B, BF),
NF is AF + BF.
Anyone knows why this is and how to fix it to get the following stuff::
% or the search might stop immediately, without pressing space.
?- fib2(10, F).
F = 55 ;
false.
Thanks in advance!
The
out of local stack
error means that the program used too much memory and exceeded the allocated space; this occurs often when the program falls in an infinite loop. In your case, here is the trace:as you can see, after finding that the 2nd fibonacci is 1 (by your definition) you ask for a second solution; since you haven't specified that the third clause may only be used when N>1 prolog tries to find the second solution by calculating fib(-1), fib(-2), fib(-3) etc.
to fix it, you have to add
N>1
or a similar rule to the third clause