Prolog 否定

5

我是一名有用的助手,可以为您翻译文本。

我正在尝试解决一个使用否定的Prolog简单查询,但我无法解决它。查询是“查找从未销售过的类别”。

知识库如下:

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(juice_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).

1
感谢Sam Segers。你的答案似乎是正确和最好的选项。Kareel,你的似乎在逻辑上是正确的,但它会产生错误。 - user685133
5个回答

3

Sam Segers的答案是正确的,但它将给出未售出的类别列表。 如果你不想要一个聚合,而是想要一个谓词,可以回溯所有没有销售任何商品的类别,你可以编写如下代码:

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 ?
 ).

在回溯时,此谓词将产生所有未销售任何物品的类别。

2
可能不是最有效的方式。
not_sold(Cats)  :-
    findall(Y,(sale(_,_,X,_),item(X,Y,_,_)),Sold),
    findall(C,(category(C,_,_,_,_),not(member(C,Sold))),Cats).

但我认为它应该可以工作。


2
你知道Prolog中的否定即失败(控制)谓词\+/1吗?它是true当目标无法被证明时。

使用这个谓词,任务就是找到已经销售的类别,即

is_category(C) :- category(C, _, _, _, _).
sold_category(C) :-
    is_category(C),
    item(I, C, _, _),
    sale(_, _, I, _).

并且

unsold_category(C) :- is_category(C), \+ sold_category(C).

如果您想要所有这些类别的列表,只需使用findall谓词即可。
findall(C, unsold_category(C), L).

0
如Sam Segers所提到的,您可以在表达式周围放置not()。
您还可以使用\+运算符来逻辑否定谓词:
removeItem([Head|Tail], Head, Tail).
removeItem([Head|Tail], Item, [Head|Tail2]) :-
  \+(Head = Item),
  removeItem(Tail, Item, Tail2).

0
not_sold(Cats) :-
    findall(C, (
        category(C, _, _, _, _),
        \+ (    
            item(I, C, _, _),
            sale(_, _, I, _)
        )
    ), Cats).

使用方法:

?- not_sold(Cats).
Cats = [books].

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接