Prolog规则和查询

Prolog rules and query

我需要一些帮助来查找规则 and/or 在 Prolog 中查询知识库,其中包含有关超市中顾客的信息。

例如我有:

Customer(Name,Age,Sex,Wage).

customer(John,30,M,2000).
customer(Mary,35,F,2500).
customer(Mark,40,M,2500).

invoice(Number, CostumerName, Product, Price).

invoice(001, John, Potatoes, 20).
invoice(002, John, Tomatoes, 10).
invoice(003, Mary, Soap, 50).
invoice(004, Mark, Potatoes, 20).
invoice(005, Mary, Detergent, 15).

Food(Potatoes).
Food(Tomatoes).
CleanProd(Soap).
CleanProd(Detergent).

如果我想找到一个趋势,例如,了解女性比男性购买更多清洁产品...我应该使用哪种类型或什么规则和查询?

您可以使用 findall 后跟 sort 来收集查询的唯一结果(您不希望列表中有重复的发票),然后 length 检查长度收集到的结果。

例如:

findall(X, (invoice(X, C, P, _), customer(C, _, f, _), cleanProd(P)), Xs),
sort(Xs, InvoicesOfWomenBuyingCleanProducts),
length(InvoicesOfMenBuyingCleanProducts, N).

此外,请注意变量以大写字母开头,原子以小写字母开头(也适用于谓词名称)。

如果你真的想要一个大写字母开头的原子,你必须用单引号括起来。

变量:M

原子:'M'

原子:m

例如,您可以这样重写知识库文章:

%   this is not needed, however is useful as
%   a documentation of what your predicate means:
% customer(Name,Age,Sex,Wage).

customer('John',30,m,2000).
customer('Mary',35,f,2500).
customer('Mark',40,m,2500).

% invoice(Number, CostumerName, Product, Price).

invoice(001, 'John', potatoes, 20).
invoice(002, 'John', tomatoes, 10).
invoice(003, 'Mary', soap, 50).
invoice(004, 'Mark', potatoes, 20).
invoice(005, 'Mary', detergent, 15).

food(potatoes).
food(tomatoes).
cleanProd(soap).
cleanProd(detergent).