Created
March 21, 2017 13:08
-
-
Save DadgadCafe/07b0b50bf9537522fed09b3dc8df2784 to your computer and use it in GitHub Desktop.
continuation demo.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(define call/cc call-with-current-continuation) | |
;;;;;;;;;;;;;; | |
(call/cc (lambda (cont) 2)) ; 2, cont do nothing | |
(call/cc (lambda (cont) (cont 2))) ; 2, cont do nothing | |
(* 3 (call/cc (lambda (cont) | |
(+ 1 2)))) ; 9, cont is not used | |
(* 3 (call/cc (lambda (cont) | |
(cont 2)))) ; 6, cont = (* 3 ?) => (cont 2) = (* 3 2) | |
(* 3 (call/cc (lambda (cont) | |
(+ 1 (cont 2))))) ; still 6, cont = (* 3 ?) => (cont 2) = (* 3 2) | |
;;;;;;;;;;;;;; | |
(define k 'void) | |
(+ 1 (call/cc (lambda (cont) | |
(set! k cont) ;; set x to the cont (+ 1 ?) ... | |
2))) | |
(k 3) ;; (+ 1 3) -> 4 | |
(+ 100 (x 3)) ;; still 4, cont = (+ 100 ?)... is replaced by (+ 1 ?)... | |
;;;;;;;;;;;;;; | |
(define (fact n) | |
(if (= n 1) | |
1 | |
(* n (call/cc (lambda (cont) | |
(cont (fact (- n 1)))))))) | |
(fact 5) ; cont = (* n (* (- n 1) (* (- n 2) ...? ))) => n * (n - 1) ... 1 | |
(define (fact n) | |
(let ((r 1) (k 'void)) | |
(call/cc (lambda (cont) | |
(set! k cont) )) | |
(set! r (* r n)) | |
(set! n (- n 1)) | |
(if (= n 1) | |
r | |
(k 'rec)))) ; 'rec does nothing , cont must be called by more than 1 arg. | |
(fact 5) | |
; (k 'rec) => process below the call/cc ... | |
;; (set! r (* r n)) | |
;; (set! n (- n 1)) | |
;; (if (= n 1) | |
;; r | |
;; (k 'rec)) | |
; => r = n * (n - 1) ... 1 | |
;;;;;;;;;;;;;; | |
(define (foo) | |
(let ((x (call/cc (lambda (cont) | |
(display "called") | |
(cont 5) ; cont is outer of the call/cc | |
(display "not called"))))) | |
(display "called2") | |
x)) | |
(foo) ; called called2 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment