我收到了以下事件:项目(C,X,G,P),(其中C
是产品编号,X
& #39;的名称,G
它的价格,P
它的费用)。
当我直接在prolog控制台上使用命令 item(n3001,_,_,P)
时,我会得到答案
G = 1.25 X = 100
但是当我写出等式p3(C)-: item(C,_,_,P).
时,我会查阅我得到的文字yes
。
我澄清的问题是,有一次我得到了P
我想要的价值,而另一次我得到它是真是假?
答案 0 :(得分:6)
There are no return values in Prolog and p3/1 does not constitute a function but a relation. Your definition
p3(C) :-
item(C,_,_,P).
reads: If item(C,_,_,P)
succeeds then p3(C)
succeeds as well. For the sake of argument, let's assume that your code includes the following fact:
item(n3001,100,1.25,1).
If you query
?- p3(n3001).
Prolog unifies C
in the head of your rule with n3001
and then tries your goal item(C,_,_,P)
which succeeds. Hence the rule succeeds and Prolog tells you:
?- p3(n3001).
yes
If you want to know the price corresponding to n3001
you have to to define a rule where P
appears in the head of the rule as well, e.g.:
p3(C,P) :-
item(C,_,_,P).
If you query that you'll get to see the value of P
corresponding to n3001
:
?- p3(n3001,P).
P = 1
If you query item/4 directly P
appears in the arguments and therefore you get to see a substitution for it that satisfies your query:
?- item(n3001,_,_,P).
P = 1