(Define (fact n) (LET (R 1) (k'void) (call/CC (lambda (C) (set! K c) (set! R (* R n) (set! N (-N 1) (if (= N 1) R (k'recurse) (Fact 5) Instructor: why can I work? Student: No! INSTRUCTOR: (call/CC (lambda (C) (set! K c) What did you do? Student: The full name of call/CC is call-with-current-continuation. It calls a single-Parameter Function and uses the current continuation as the parameter of the single-Parameter Function. Therefore, the above formula is to save the current continuation to K. INSTRUCTOR: What is the current continuation? Student: (escaper (lambda (~) (~ (Set! R (* R n) (set! N (-N 1) (if (= N 1) R (k'recurse) Instructor: how to store K? Student: (set! K (escaper (lambda (~) (~ (Set! (* R n) (set! N (-N 1) (if (= N 1) R (k'recurse) Instructor :( call/CC (lambda (C) (set! K c) and (set! K (escaper (lambda (~) (~ (Set! (* R n) (set! Can N (-N 1) (if (= N 1) R (k'recurse) be equivalent and replace with each other? Student: Yes! (Define (fact n) (LET (R 1) (k'void) (set! K (escaper (lambda (~) (~ (Set! (* R n) (set! N (-N 1) (if (= N 1) R (k'recurse); a (set! R (* R n) (set! N (-N 1) (if (= N 1) R (k'recurse); B: Why can I work? Student: After tracking (Fact 5), you will know B: n = 5 => r = 5, n = 4 [n! = 1, continue] A: N = 4 => r = 20, n = 3 [n! = 1, continue] A: n = 3 => r = 60, n = 2 [n! = 1, continue] A: N = 2 => r = 60, n = 1 [n = 1, return r and escape] INSTRUCTOR: Why is recursion? Student: Because continuation is a function that carries on recursion, this continuation function is recursive. Teacher: The continuation here is actually recursion. Although the continuation is called a Goto With context, this program can also be seen as using Goto. (Define (fact n) (LET (R 1) (k'void) (call/CC (lambda (C) (set! K c) (set! R (* R n) (set! N (-N 1) (if (= N 1) R (k'recurse); => go back to (call/CC (lambda (C) (set! (K c) Students: But this is just a metaphor. Actually, it is recursion! Teacher: You are right.
Call/CC analysis example