Javier Gonzalez-Sanchez | CSE240 | Spring 2020 | 9
jgs
Recursion | Factorial
% this is fact
factorial(0, 1).
% this is a rule
% the factorial of F is N*F1
% if N>0 and
% N1 is N-1 and
% the factorial of N1 is F1
factorial(N, F) :-
N>0,
N1 is N - 1,
factorial(N1, F1),
F is N * F1.
?- factorial (3, W).
W=6
1. factorial(3, W)
apply rule 2
2. 3>0, N1 is 3-1, factorial (N1, F1), F is 3 *F1
solve the individual parts
true, 2 is 3-1, factorial (2, F1), F is 3*F1
apply rule 2 again
3. 2>0, N2 is 2-1, factorial (N2, F2), F1 is 2 * F2
solve the individual parts
true, 1 is 2-1, factorial (1, F1), F1 is 2*F2
apply rule 2 again
4. 1>0, N3 is 1-1, factorial (N3, F3), F2 is 2 * F3
solve the individual parts
true, 0 is 1-1, factorial (0, F3), F2 is 1*F3
apply rule 1
5. factorial (0, 1)
F3 is 1
6. Go back, replace F3 to get F2, then F2 to get F1,
then F1 to get F.