Search code examples
prologinstantiation-error

Prolog arguments are not sufficiently instantiated (function which calculates list length)


I made a function which calculates a list length. Below is my code.

listLength(LIST) :- solve(LIST, LENGTH), write(LENGTH).
solve([], _).
solve([_|T], LENGTH) :- ADD is LENGTH + 1, solve(T, ADD).

When I run this code with input

?- listLength([1, 2, 3, 4, 5, 6, 7]).

then, interpreter showed me error message solve/2 : Arguments are not sufficiently instantiated.

when I modified above code like below.

listLength(LIST) :- LENGTH is 0, solve(LIST, LENGTH), write(LENGTH).
solve([], _).
solve([_|T], LENGTH) :- ADD is LENGTH + 1, solve(T, ADD).

When I run this code with the same input, then always 0 is written.

I want to calculate LENGTH, and I want to use the variable in listLength function.

What's wrong with me? ( Please kindly note that I am using swi-prolog. )


Solution

  • The first mistake is in the base case. Instead of solve([], _). you should write solve([], 0). because if you don't know the length of empty list how will you find recursively for bigger lists.

    There is also another issue in :

    solve([_|T], LENGTH) :- ADD is LENGTH + 1, solve(T, ADD).
    

    when trying to calculate ADD is LENGTH + 1 length is not instantiated-calculated. You need to change the order like:

    listLength(LIST) :- solve(LIST, LENGTH), write(LENGTH).
    solve([], 0).
    solve([_|T], LENGTH) :- solve(T, ADD), LENGTH  is ADD+ 1.
    

    Now querying:

    ?- listLength([1, 2, 3, 4, 5, 6, 7]).
    7
    true.