Why is this prolog query both true and false?

那年仲夏 提交于 2019-11-30 06:13:00

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

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.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!