Prolog阶乘递归 [英] Prolog factorial recursion

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

问题描述

我无法理解以下析因程序

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阶乘递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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