This is my code:-
fib(0,0).
fib(1,1).
fib(F,N) :-
N>1,
N1 is N-1,
N2 is N-2,
F is F1+F2,
fib(F1,N1),
fib(F2,N2),
write(F," ,").
On consulting in GNU Prolog, I am getting:
| ?- consult('C:/GNU-Prolog/bin/fib.pl').
compiling C:/GNU-Prolog/bin/fib.pl for byte code...
C:/GNU-Prolog/bin/fib.pl compiled, 3 lines read - 1253 bytes written, 15 ms
yes
| ?- fib(F,2).
uncaught exception: error(instantiation_error,(is)/2)
Instantiation error is caused by the attempt to calculate F
before the values of F1
and F2
have been determined. The simplest solution would to move F is F1+F2
after the recursive calls such that your program becomes
fib(0,0).
fib(1,1).
fib(F,N) :-
N>1,
N1 is N-1,
N2 is N-2,
fib(F1,N1),
fib(F2,N2),
F is F1+F2,
write(F," ,").
(thanks to @mbratch for reminding) write
has only one argument, i.e., write(F," ,").
should be write(F), write(" ,").
You should be however careful with the output. The program above would print out the same value multiple times: e.g., to calculate fib(F,3)
it will invoke fib(F1,2)
and fib(F2,1)
while fib(F1,2)
will invoke fib(F11,1)
and fib(F12,1)
resulting in the following output 1, 1, 2, 1, 3
. Is this really what you need?
You probably need F is F1+F2
after having instantiated F1
and F2
. The following is an exact adaptation of your code to something that works. Now, I'm sure it's exactly what you want (besides, it fails for large values of N, large being impressively small here).
fib(0,0).
fib(1,1).
fib(F,N) :-
N>1,
N1 is N-1,
N2 is N-2,
fib(F1,N1),
fib(F2,N2),
F is F1+F2,
format('~w, ',[F]).
I used format
instead of write
, I'm not sure that write/2
does what you expect.
fab1(1,1).
fab1(2,1).
fab1(N,T):-
N>2,
N1 is N-1,
N2 is N-2,
fab1(N1,T1),
fab1(N2,T2),
T is (T1+T2),
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With