Created
November 27, 2017 12:50
-
-
Save cjsmeele/cdbd2639a9cb4040375e703b5b69f97d to your computer and use it in GitHub Desktop.
Scheme generator macro
This file contains 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-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