I am trying to solve a simple query in Prolog that uses negation but I can't crack it. The query is "Find the categories that have never been sold".
The knowledge base is as follows:
category(stationery, 30, 200, 10, 2).
category(books, 10, 30, 3, 2).
category(consumables, 50, 300, 15, 3).
item(pen, stationery, 10, 150).
item(colgate_small, consumables, 20, 65).
item(colgate_medium, consumables, 45, 70).
item(colgate_big, consumables, 70, 34).
item(juice_small, consumables, 45, 23).
item(ju开发者_StackOverflowice_medium, consumables, 60, 23).
item(juice_big, consumables, 80, 12).
item(book, stationery, 5, 65).
item(pencil, stationery, 7, 56).
item(newspaper, books, 50, 400).
sale(tom, 1/1/07, pen, 3).
sale(peter, 1/1/07, book, 85).
sale(peter, 1/1/07, juice_small,1).
sale(alice, 7/1/07, pen, 10).
sale(alice, 7/1/07, book, 5).
sale(patrick, 12/1/07, pen, 7).
Sam Segers answer is correct, though it will give you the list of categories not sold. If you don't want an aggregation but rather a predicate which will backtrack over all the categories which do not have any items sold you would write something like this:
not_sold(Cat):-
category(Cat,_,_,_,_), % Get one category at a time
\+ ( % Applies negation
item(Item, Cat,_,_), % Check for items in this category
sale(_,_,Item,_) % Has the item been sold ?
).
This predicate, upon backtracking, will yield all the categories for which no items where sold.
Might not be the most efficient way.
not_sold(Cats) :-
findall(Y,(sale(_,_,X,_),item(X,Y,_,_)),Sold),
findall(C,(category(C,_,_,_,_),not(member(C,Sold))),Cats).
But I think it should work.
Are you aware of Prolog's negation-as-failure (control) predicate, \+/1? It is true
iff the goal cannot be proven.
Using the predicate, the task reduces to finding categories that have been sold, i.e.
is_category(C) :- category(C, _, _, _, _).
sold_category(C) :-
is_category(C),
item(I, C, _, _),
sale(_, _, I, _).
and
unsold_category(C) :- is_category(C), \+ sold_category(C).
If you want a list of all those categories, simply use the findall predicate.
findall(C, unsold_category(C), L).
As Sam Segers mentioned you can put a not() around an expression.
You can also use the \+ operator to logically negate a predicate:
removeItem([Head|Tail], Head, Tail).
removeItem([Head|Tail], Item, [Head|Tail2]) :-
\+(Head = Item),
removeItem(Tail, Item, Tail2).
not_sold(Cats) :-
findall(C, (
category(C, _, _, _, _),
\+ (
item(I, C, _, _),
sale(_, _, I, _)
)
), Cats).
Usage:
?- not_sold(Cats).
Cats = [books].
精彩评论