问题描述
我无法理解以下析因程序
I'm having trouble understanding the following factorial program
fact1(0,Result) :-
Result is 1.
fact1(N,Result) :-
N > 0,
N1 is N-1,
fact1(N1,Result1),
Result is Result1*N.
当调用fact1
嵌套在第二个fact1
中时,这是否表示从不调用最后一行Result is Result1*N.
?还是在Prolog中,最后一行是在递归调用之前执行的?
When fact1
is called nested within the second fact1
, doesn't that mean that the the last line, Result is Result1*N.
, is never called? Or in Prolog does the last line get executed before the recursive call?
推荐答案
否,递归调用首先发生!它必须这样做,否则最后一个子句是没有意义的.该算法可分解为:
No, the recursive call happens first! It has to, or else that last clause is meaningless. The algorithm breaks down to:
factorial(0) => 1
factorial(n) => factorial(n-1) * n;
如您所见,您需要在进行乘法运算之前计算递归的结果,以返回正确的值!
As you can see, you need to calculate the result of the recursion before multiplying in order to return a correct value!
您的prolog实现可能具有启用跟踪的方法,这将使您看到整个算法正在运行.这可能会帮助您.
Your prolog implementation probably has a way to enable tracing, which would let you see the whole algorithm running. That might help you out.
这篇关于Prolog阶乘递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!