Skip to content

Instantly share code, notes, and snippets.

@cjsmeele
Created November 27, 2017 12:50
Show Gist options
  • Save cjsmeele/cdbd2639a9cb4040375e703b5b69f97d to your computer and use it in GitHub Desktop.
Save cjsmeele/cdbd2639a9cb4040375e703b5b69f97d to your computer and use it in GitHub Desktop.
Scheme generator macro
(define-macro generator
(lambda (params . body)
(let ((cont (gensym "gen-cont"))
(yieldc (gensym "gen-yield")))
`(lambda ,params
(let ((,cont #f))
;; cont will point to the last yield call.
(lambda ()
(let/cc ,yieldc
;; yieldc returns from the generator.
(if ,cont (,cont ,yieldc))
(let-syntax
((yield (syntax-rules ()
((yield val)
;; Yield syntax: Update cont and return a value.
;; yieldc is set to the cc when the gen is re-entered.
(set! ,yieldc (let/cc x (set! ,cont x) (,yieldc val)))))))
,@body))))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment