1
votes

I am trying to right a predicate in Prolog that accepts an item, a list, and a number, and checks to see if the item is in the list that number of times. For example

count(7,[3,7],X).

would return X=1.

count(7,[3,7],1).

would return true

This is what I have so far

count_occur(A,[0|B],D).
count_occur(A,[A|C],D) :- count_occur(A,C,D1), D is D1+1.
count_occur(A,[B|C],D) :- count_occur(A,C,D).

I am very new to Prolog and really struggling to understand this programming paradigm.

What I am trying to do is to see if the first item in the list matches the passed-in value (A), if it does increment D and check again against the remainder of the list. This is how I would do it in lisp or another language anyway. Could really use some help, been at this for a while and it just isn't clicking for me.

1
What is the purpose of the first line? And you have to handle the case of having an empty list. - daniel kullmann

1 Answers

1
votes

I don't have prolog right now to test it, but I would try it like that:

count_occur(A, [], 0).
count_occur(A, [A|T], D):- count_occur(A, T, D1), D is D1 + 1.
count_occur(A, [B|T], D):- A \= B, count_occur(A, T, D).

The idea is that if the list is empty, there is 0 occurrences of each element. The rest is almost the same as yours as I think that it is correct.

The only difference is that I have added A \= B, which should mean A \neq B. I think that otherwise it will accept A == B, which might lead to count_occur(3, [3], 0). being true. You should check about that.

I hope this helps!