1

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. 
2
  • Try using gtrace with SWI-Prolog. Commented Jan 16, 2023 at 17:44
  • Prolog's inference engine does that for us, happily. Seen with e.g. gtrace - swi-prolog.org/pldoc/man?section=debugger Commented Jan 16, 2023 at 17:49

1 Answer 1

4

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 F1s are cleared out.

Sign up to request clarification or add additional context in comments.

1 Comment

The hardest connection for me to make was that the value of F is actually the value of F1 in an initially called factorial(N1, F1), hence when F is assigned F1 gets consecutively assigned in the previous predicate . And this is how the value of F1 is "remembered", your explanation really cleared that bit up, thanks a lot.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.