Reputation: 706
I have a set of facts in Prolog, such that:
likes(alice, burger).
likes(bob, burger).
likes(charlie, burger).
likes(bob, sandwich).
likes(charlie, sandwich).
likes(alice, muffin).
I want to know what's the most popular dish (burgers in the example above). I'm not interested in the 2nd, 3rd, etc most popular for this query as the list of preferences can be really long.
I'm struggling to write this query in SWI-Prolog. Can you help me?
Upvotes: 0
Views: 55
Reputation: 28983
most_popular(Popular) :-
findall(X, likes(_, X), Xs),
sort(0, @=<, Xs, Items),
clumped(Items, Counts),
sort(2, @>=, Counts, [Popular|_]).
sort/4
first parameter is which part of the term to sort by. Item-Count
is really the compound -(Item,Count)
so 0 sorts with normal term sorting, 1 gets the Item name to sort by or 2 gets the Count to sort by) and unify the first element of the resulting list as the answer.?- most_popular(Item-Count).
Count = 3,
Item = burger
Upvotes: 1