Prolog 程序返回 false [英] Prolog program returns false

查看:57
本文介绍了Prolog 程序返回 false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Prolog 中实现了以下电源程序:

I implemented the following power program in Prolog:

puissance(_,0,1).
puissance(X,N,P) :- N>0,A is N-1, puissance(X,A,Z), P is Z*X.

代码做了应该做的事情,但在正确的答案之后,它打印出false".我不明白为什么.我正在使用 swi-prolog.

The code does what is supposed to do, but after the right answer it prints "false.". I don't understand why. I am using swi-prolog.

推荐答案

您可以在您的解决方案中添加 cut 运算符(即 !),这意味着 prolog 不应尝试在达到这一点的第一次成功统一之后,回溯并找到更多解决方案.(即您正在修剪解决方案树).

You can add a cut operator (i.e. !) to your solution, meaning prolog should not attempt to backtrack and find any more solutions after the first successful unification that has reached that point. (i.e. you're pruning the solution tree).

puissance(_,0,1) :- !.
puissance(X,N,P) :- N>0,A is N-1, puissance(X,A,Z), P is Z*X.

<小时>

外行的解释:

prolog 试图查看是否还有更多解决方案的原因是:

The reason prolog attempts to see if there are any more solutions, is this:

在你的递归中最后一次调用 puissance 时,first puissance 子句成功,因为 P=1,你一路旅行回到顶部调用以与 P 与该选择产生的最终值执行统一.

At the last call to puissance in your recursion, the first puissance clause succeeds since P=1, and you travel all the way back to the top call to perform unification with P with the eventual value that results from that choice.

然而,对于最后一次对 puissance 的调用,Prolog 没有机会检查 second puissance 子句是否会 是可满足的并可能导致不同的解决方案,因此除非您告诉它不要检查进一步的解决方案(通过在成功后对第一个子句使用切割),它有义务返回那一点,也检查第二个子句.

However, for that last call to puissance, Prolog didn't have a chance to check whether the second puissance clause would also be satisfiable and potentially lead to a different solution, therefore unless you tell it not to check for further solutions (by using a cut on the first clause after it has been successful), it is obligated to go back to that point, and check the second clause too.

一旦这样做,它就会发现第二个子句无法满足,因为 N = 0,因此该特定尝试失败.

Once it does, it sees that the second clause cannot be satisfied because N = 0, and therefore that particular attempt fails.

因此,false"实际上意味着 prolog 也检查了其他选择点,并且无法以任何其他方式统一 P 以满足它们,即 P 没有更多有效的统一.

So the "false" effectively means that prolog checked for other choice points too and couldn't unify P in any other way that would satisfy them, i.e. there are no more valid unifications for P.

而且,您首先可以选择寻找其他解决方案的事实,确切地说,还有其他可能具有可满足条款的路线尚未探索.

And the fact that you're given the choice to look for other solutions in the first place, exactly means that there are still other routes with potentially satisfiable clauses remaining that have not been explored yet.

这篇关于Prolog 程序返回 false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆