Search code examples
prologlogicfibonaccideclarativeclpfd

Why does this Prolog Fibonacci function cause a "instantiation_error"?


I am trying to calculate the Fibonacci series using the following function:

fib(0,A,_,A).
fib(N,A,B,F) :-
    N1 is N-1, Sum is A+B, fib(N1, B, Sum, F).
fib(N, F) :- fib(N, 0, 1, F).

This is intended to works like this:

| ?- fib(20,Result).

Result = 6765 ? 

But when I try this, it complains:

| ?- fib(What,6765).
uncaught exception: error(instantiation_error,(is)/2)

Does anyone understand why this is happening?


Solution

  • In the second clause:

    fib(N,A,B,F) :-
        N1 is N-1, Sum is A+B, fib(N1, B, Sum, F).
    

    N is a variable to be decremented, and in your call to:

    fib(What, 6765).
    

    The variable is not yet defined, so you get the instantiation error on N1 is N - 1.

    In swipl I do even get the error:

    ?- fib(W, 6765).
    ERROR: fib/4: Arguments are not sufficiently instantiated