为什么这个序言查询既正确又错误?
我的 SWI-Prolog 知识库包含以下两个事实:
f(a,b).
f(a,c).
现在,如果我提出查询
?- f(a,c).
true.
但是
?- f(a,b).
true ;
false.
为什么 f(a,b) 既为真又为假?当知识库中有三个事实时也会发生这种情况。如果我附加 f(a,d)。对于 KB,则 f(a,d) 为真(仅),但 f(a,b) 和 f(a,c) 既为真又为假。发生了什么事,我该怎么做才能让 Prolog (仅)真实地回答这些查询?
My SWI-Prolog knowledge base contains the following two facts:
f(a,b).
f(a,c).
Now if I pose the query
?- f(a,c).
true.
But
?- f(a,b).
true ;
false.
Why is f(a,b) both true and false? This also happens when there are three facts in the KB. If I append f(a,d). to the KB, then f(a,d) is true (only), but f(a,b) and f(a,c) are both true and false. What's going on, and what can I do so that Prolog answers (only) true to these queries?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
(注意:这个答案有点猜测)
考虑 Prolog 如何确定
f(a,c)
是否为真。它检查第一条规则f(a,b)
,但未找到匹配项,但第二条规则f(a,c)
匹配。因此,f(a,c)
为真。此外,由于f
不再有规则,因此允许回溯发生是没有意义的——没有其他可能的解决方案。现在考虑
f(a,b)
。 Prolog 将检查第一条规则,并找到匹配项。因此,f(a,b)
为真。然而,并非所有规则都已用尽。因此,Prolog 将允许搜索继续(如果您点击;
)。当您继续搜索并回溯时,它会发现其余规则,特别是f(a,c)
,与f(a,b)
不匹配。因此,结果是假的。(Note: this answer is somewhat of a guess)
Consider how Prolog determines whether
f(a,c)
is true or not. It checks the first rule,f(a,b)
, and doesn't find a match, but the second rule,f(a,c)
matches. Therefore,f(a,c)
is true. Furthermore, since there are no more rules forf
, there is no point in allowing a backtrack to occur -- there are no other possible solutions.Now consider
f(a,b)
. Prolog will check the first rule, and find a match. Therefore,f(a,b)
is true. However, not all rules have been exhausted. Therefore, Prolog will allow the search to continue (if you hit;
). When you do continue the search and backtrack, it will discover that the remaining rules, specificallyf(a,c)
, do not matchf(a,b)
. Therefore, the result is false.除了迈克尔·威廉姆森的回答之外。如果你想告诉 Prolog 在第一次成功命中后停止寻找答案,那么使用 cut (
!
):Just in addition to Michael Williamson's answer. If you want to tell Prolog to stop looking for answers after the first successful hit, then use the cut (
!
):