Call/CC analysis example

Source: Internet
Author: User
(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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.