fib(0,0).
fib(1,1).
fib(A,Result):-
fib(A-1,R),
fib(A-2,P),
Result is R+P.

- 10,264
- 13
- 101
- 209

- 23
- 4
-
Your program does not stop. Consider performing a Cut. – Hanif Bin Ariffin Mar 06 '19 at 17:38
2 Answers
To understand why, first narrow down the reason for non-termination. Here is the smallest part of your program that still loops:
fib(0,0) :- false.fib(1,1) :- false. fib(A,Result):- fib(A-1,R), false,fib(A-2,P),Result is R+P.
No matter what the arguments are, this program will loop. And thus your original program will loop too.
To fix this you need to change something in the visible part: You need to ensure that A > 1
. In this manner the program now terminates.
Further, as noted correctly by @andsanmar, A-1
alone is not a number, but just the term -(A,1)
so it can never be 0
nor 1
. So either write
fib(N,0) :- N =:= 0.
fib(N,1) :- N =:= 1.
...
Or add (is)/2
as suggested by @andsanmar.
For more on how to narrow down reasons for non-termination see failure-slice.

- 10,264
- 13
- 101
- 209
When you do fib(A-1,R)
, being A=4, for example, what's going to be sent is 4-1 instead of 3, you need to do Aminus1 is A -1, fib(Aminus1,R)
. The same with the A-2

- 1
- 3