Prolog - Arguments are not sufficiently instantiated

Eddwhis picture Eddwhis · May 22, 2014 · Viewed 50.5k times · Source

I am writing a little program which counts how many elements in a list are not numbers. Here is my code:

not_number([],0).
not_number([X|T],R):- 
    not(number(X)),
    R1 is R+1,  
    not_number(T,R1). 

not_number([_|Tail],Result):-
    not_number(Tail,Result).  

If I execute code like this :

?- not_number([1,2,3,5], R).

I am getting that R = 0 (as it should be)

R = 0.

But if I put a character in the list:

?- not_number([1,2,3,5,a], R).

then I am getting this error:

ERROR: not_number/2: Arguments are not sufficiently instantiated
   Exception: (10) not_number([a], _G247) ? 

Can someone explain whats wrong with code? I am new to prolog.

Answer

Rialgar picture Rialgar · Dec 14, 2015

I am writing this answer, because the best answer yet was in a comment by lurker. I want to have it show up as an actual answer.

Your code is not working, because you're doing R1 is R+1 when R isn't instantiated in the case not_number([X|T], R). Your recursive case is strung a little backwards. You want to do this:

not_number([X|T],R):- 
    not(number(X)),
    not_number(T,R1),
    R is R1+1.

Now the right side of the is is instantiated when it is called.