experiments/bidi-generator.ss
author Tony Garnock-Jones <tonygarnockjones@gmail.com>
Wed, 16 Jan 2019 17:15:58 +0000
changeset 438 1fe179d53161
parent 283 94f780251884
permissions -rw-r--r--
Add missing primitive implementation for the plain interpreter.

#lang scheme

(provide yield generator)

(define current-yielder
  (make-parameter
   (lambda (v)
     (error 'yield "must be called in the context of a generator"))))

(define (yield . vals)
  (apply (current-yielder) vals))

(define-syntax-rule (generator init-formals body0 body ...)
  (letrec ((yielder (lambda vals
                      (call-with-current-continuation
                         (lambda (new-inner-k)
                           (set! inner-k new-inner-k)
                           (apply outer-k vals)))))
           (outer-k #f)
           (inner-k (lambda init-formals
                      (call-with-values
                       (lambda ()
                         (parameterize ((current-yielder yielder))
                           body0 body ...))
                       (lambda results
                         (set! inner-k (lambda ignored (error "Generator is terminated")))
                         (apply outer-k results))))))
    (lambda args
      (call-with-current-continuation
       (lambda (new-outer-k)
         (set! outer-k new-outer-k)
         (apply inner-k args))))))