Search code examples
recursionprologfactorial

factorial (recursion in general) in prolog - why order of terms matters


Why this factorial implementation doesn't work:

factorial(0, B) :- B is 1.
factorial(A, B) :-
                   A > 0,
                   Ax is A-1,
                   B is A*Bx,
                   factorial(Ax, Bx).

And this works:

factorial2(0, B) :- B is 1.
factorial2(A, B) :-
                   A > 0,
                   Ax is A-1,
                   factorial2(Ax, Bx),
                   B is A*Bx.

Solution

  • Because is/2 needs the right hand side to be fully instantiated.

    In your first example Bx is not instantiated and is used in the right hand side whereas in your second example it is used after it gets instantiated.