0
votes

I am new in Prolog and I am stucked in a problem. I have following facts:

_________________
likes(a,apple).
likes(a,banana).
likes(a,orange).
_________________

and my query will be:

counts(a,Var).

where Var = [apple,banana,orange]. I don't want in this manner that

Var=apple ;
Var=banana;
Var=orange;

Any suggestions or help will be appreciated. Thanks in advance.

2
what do you want to get? Is it the count of people who like apple/banana/orange?Asterisk

2 Answers

1
votes

I would resort to the almighty findall/3 to solve your problem.

?- findall(Fruit, likes(a, Fruit), Fruits), length(Fruits, N).

Fruits = [apple,banana,orange]
N = 3

So your counts(a, Var) is just a findall/3 call (even if it really collects instead of counting):

counts(Person, Fruits) :- findall(Fruit, likes(Person, Fruit), Fruits).

And you get the following as a result:

?- counts(a, Var).

Var = [apple,banana,orange]
0
votes

If I understand you correctly you want to count number of entities that like fruits given as a list. So, then the code will be something like this:

likes(a,apple).
likes(a,banana).
likes(a,orange).

counts(a, [_], 1).
counts(a, [H|T], Count) :- likes(a, H), counts(a, T, Count1), Count is 1 + Count1, !.