Find the number of Ns in the list

So, I am trying to create a method that determines the number of Ns in a list. I've been experimenting for an hour or so now and can't seem to get something solid. At the moment I have 0. I think it might be related to my base but I cannot figure it out. Logic programming like prologue is a new horizon for me, so any help would be great.

% base case returns 0 occurrences for empty list
numN(_,[],0).
numN(N,[Y | T], A) :- N == Y, numN(N,T,A2), A is A2+1.
numN(N, [Y | T], A) :- Y \= N, numN(N,T,A).



?- numN(X, [a,X,l,g,X], N).
N = 3.

      

when it should be 2. When I change the basecase to -1 then it returns the correct value.

+3


source to share


2 answers


Here's one solution using a battery:

%returns number of elements E in list L
numN(E,L,N) :- numN2(E,L,0,N).

numN2(E,[],Ak,Ak).
numN2(E,[E|Xs],Ak,N) :- !, Ak1 is Ak+1, numN2(E,Xs,Ak1,N).
numN2(E,[X|Xs],Ak,N) :- numN2(E,Xs,Ak,N).

      



Edited solution, thanks @migfilg :)

+1


source


In your last two sentences, N

it is used as a free variable, so sentence 2 always succeeds because it is N

combined with any term in the head of the list, and your program's solution as it stands will be the length of the list, regardless of its content. In the last sentence, you probably have a typo as @repeat comment above: do numX/2

you want to call?



What you need is to have a new argument in your predicate representing the term you need to count.

0


source







All Articles