为什么这个序言查询既正确又错误?

发布于 2024-09-11 13:06:54 字数 341 浏览 2 评论 0原文

我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

烟雨凡馨 2024-09-18 13:06:54

(注意:这个答案有点猜测)

考虑 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 for f, 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, specifically f(a,c), do not match f(a,b). Therefore, the result is false.

前事休说 2024-09-18 13:06:54

除了迈克尔·威廉姆森的回答之外。如果你想告诉 Prolog 在第一次成功命中后停止寻找答案,那么使用 cut (!):

?- f(a, b), !.
true.

?- f(a, c), !.
true.

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 (!):

?- f(a, b), !.
true.

?- f(a, c), !.
true.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文