I am trying to count how many times a element appears in a list, so far I have came up with
rate(X,[H|T],N):-
X == H,
N is N+1,
rate(X,T,N).
rate(X,[_|T],N) :-
rate(X,T,N).
rate(_,[],N) :-
N is 0.
I’ve covered when the a match is found, when there isn’t a match and when it reaches the end of the list. But when i test i get
43 ?- rate(4,[4,2,3,4,4,2],X).
ERROR: is/2: Arguments are not sufficiently instantiated
Exception: (6) frequency(4, [4, 2, 3, 4, 4, 2], _G393) ?
What arguments am i missing exactly?
You can use
is/2(like inN is X) if and only if X is a number. You can’t useis/2if X is a free variable. In your first clause you have:N is N+1. This is bad, since N is a free variable (it has not a value at this point, and so is for N+1).There’s another error. In:
since you use this ONLY when X is not the first element in the list, you should check for this to be true! Here’s the code: