Last active
August 22, 2019 21:41
-
-
Save rileylev/fd520ad2b604b23cd48bb030d2bac402 to your computer and use it in GitHub Desktop.
generators with macros
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-syntax-parameter yield | |
(lambda (stx) | |
(syntax-violation 'yield "~yield~ is undefined outside of a generator" stx))) | |
(define-syntax-rule (generator body ...) | |
(let () | |
(define yield-tag (make-prompt-tag)) | |
(define (yield% . returns) | |
(apply abort-to-prompt yield-tag returns)) | |
(define (thunk) | |
(syntax-parameterize ((yield (identifier-syntax yield%))) | |
body ...)) | |
(define this-step thunk) | |
(lambda () | |
(call-with-prompt yield-tag | |
this-step | |
(lambda (next-step . args) | |
(set! this-step next-step) | |
(apply values args)))) | |
(define count | |
(generator | |
(let loop ((i 0)) | |
(yield i) | |
(loop (1+ i))))) | |
(count) => 0 | |
(count) => 1 | |
(count) => 2 | |
(count) => 3 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment