I can't seem to wrap my head around how this works, to be specific I don't understand how F1 represents the value of (N-1)! cause the way I see it once we reach the base case the value of F1 stays at 1 seeing as to how it is never reassigned. I just want to understand for instance if N = 4
, how once we reach the base case the value of F1 goes from 1 to 2 to 6.
factorial(0,1).
factorial(N,F) :-
N>0,
N1 is N-1,
factorial(N1,F1),
F is N * F1.
CodePudding user response:
the value of F1 stays at 1
how the value of F1
The secret is that you need plural not singular; when running your code, Prolog makes many variables named F1
, one for each intermediate value. Each call to factorial(N1, F1)
adds a new layer to the call stack, with a new copy of all the variables which factorial/2
uses. They have the same names, but they are separate in memory and can be bound to different values.
This is the same stack which can grow too big in unbounded recursion and overflow, giving a stackoverflow error, the name of this website.
F is 4 * F1_a
F1_a is 3 * F1_b
F1_b is 2 * F1_c
F1_c is 1 * F1_d
F1_d = 1
The stack is built up in memory, then when the base case is reached the code can move on to F is N * F1.
and the stack collapses down and the intermediate F1
s are cleared out.