Prolog factorial recursion

后端 未结 8 1887
無奈伤痛
無奈伤痛 2021-01-11 12:16

I\'m having trouble understanding the following factorial program

fact1(0,Result) :-
    Result is 1.
fact1(N,Result) :-
    N > 0,
    N1 is N-1,
    fac         


        
8条回答
  •  感情败类
    2021-01-11 12:48

    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!

    Your prolog implementation probably has a way to enable tracing, which would let you see the whole algorithm running. That might help you out.

提交回复
热议问题