Skip to content

Instantly share code, notes, and snippets.

@rileylev
Last active August 22, 2019 21:41
Show Gist options
  • Save rileylev/fd520ad2b604b23cd48bb030d2bac402 to your computer and use it in GitHub Desktop.
Save rileylev/fd520ad2b604b23cd48bb030d2bac402 to your computer and use it in GitHub Desktop.
generators with macros
(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