Skip to content

Instantly share code, notes, and snippets.

@danking
Last active December 12, 2015 05:18
Show Gist options
  • Select an option

  • Save danking/4720774 to your computer and use it in GitHub Desktop.

Select an option

Save danking/4720774 to your computer and use it in GitHub Desktop.
continuation hackery
#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))
@danking
Copy link
Author

danking commented Feb 6, 2013

You could also implement lbl and goto like this, with the slight exception that you no longer capture the binding in the continuation.

(define-syntax lbl
  (syntax-rules ()
    ((_ name)
     (define name #f)
     (let/cc k (set! name k)))))

(define-syntax goto
  (syntax-rules ()
    ((_ label-name)
     (label-name))))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment