Prolog factorial recursion

后端 未结 8 1841
無奈伤痛
無奈伤痛 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:32

    I would do something like:

    fact(0, 1).
    fact(N, Result):-
        Next is N - 1,
        fact(Next, Recursion),
        Result is N * Recursion.
    

    And a tail version would be like:

    tail_fact(0, 1, 0).         /* when trying to calc factorial of zero */
    tail_fact(0, Acc, Res):-    /* Base case of recursion, when reaches zero return Acc */
         Res is Acc.
    tail_fact(N, Acc, Res):-    /* calculated value so far always goes to Acc */
         NewAcc is N * Acc,
         NewN is N - 1,
         tail_fact(NewN, NewAcc, Res).
    

    So for you to call the:

    non-tail recursive method: fact(3, Result).

    tail recursive method: tail_fact(3, 1, Result).

    This might help ;)

提交回复
热议问题