Last active
December 12, 2015 05:18
-
-
Save danking/4720774 to your computer and use it in GitHub Desktop.
continuation hackery
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
| #lang racket | |
| ;; 03. pvar a = 0; | |
| ;; 04. [lbl] topOfLoop: | |
| ;; 05. a++; | |
| ;; 06. if (a < 292 ) { | |
| ;; 07. goto topOfLoop; | |
| ;; 08. } | |
| (let ((a 0)) | |
| ;; (let/cc k k) returns the continuation at this point, which is to say that | |
| ;; calling (top-of-loop VALUE) will return to the let form and bind | |
| ;; top-of-loop to VALUE and then do the set! and the if, again | |
| (let ((top-of-loop (let/cc k k))) | |
| (set! a (add1 a)) | |
| (if (< a 292) | |
| ;; we want to go back to the top of the loop and we want the label to | |
| ;; stay the same. we could change the continuation as we're going, but | |
| ;; that's not how labels work | |
| (top-of-loop top-of-loop) | |
| ;; when we're finally done, just return some value | |
| (list 'done a)))) | |
| (define-syntax lbl | |
| (syntax-rules () | |
| ((_ name) | |
| (define name (let/cc k k))))) | |
| (define-syntax goto | |
| (syntax-rules () | |
| ((_ label-name) | |
| (label-name label-name)))) | |
| (define (tryit) | |
| (define a 0) | |
| (lbl topOfLoop) | |
| (set! a (add1 a)) | |
| (if (a . < . 292) | |
| (goto topOfLoop) | |
| (list 'done a))) | |
| (tryit) | |
| ;; or | |
| (let ((a 0)) | |
| (lbl topOfLoop) | |
| (set! a (add1 a)) | |
| (if (a . < . 292) | |
| (goto topOfLoop) | |
| (list 'done a))) | |
| ;; or | |
| (define (tryit) | |
| (define a 0) | |
| (lbl topOfLoop) | |
| (set! a (add1 a)) | |
| (when (a . < . 292) | |
| (goto topOfLoop)) | |
| (list 'done a)) | |
| ;; or | |
| (let ((a 0)) | |
| (lbl topOfLoop) | |
| (set! a (add1 a)) | |
| (when (a . < . 292) | |
| (goto topOfLoop)) | |
| (list 'done a)) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You could also implement lbl and goto like this, with the slight exception that you no longer capture the binding in the continuation.