[ create a new paste ] login | about

Link: http://codepad.org/2K8TPKn9    [ raw code | output | fork ]

programmingpraxis - Scheme, pasted on Jul 28:
(define-syntax define-generator
  (lambda (x)
    (syntax-case x (lambda)
      ((stx name (lambda formals e0 e1 ...))
         (with-syntax ((yield (datum->syntax-object (syntax stx) 'yield)))
           (syntax (define name
             (lambda formals
               (let ((resume #f) (return #f))
                 (define yield
                   (lambda args
                     (call-with-current-continuation
                      (lambda (cont)
                        (set! resume cont)
                        (apply return args)))))
                 (lambda ()
                   (call-with-current-continuation
                    (lambda (cont)
                      (set! return cont)
                      (cond (resume (resume))
                      (else (let () e0 e1 ...)
                            (error 'name "unexpected return"))))))))))))
        ((stx (name . formals) e0 e1 ...)
          (syntax (stx name (lambda formals e0 e1 ...)))))))

(define-generator (test-gen)
  (yield 1)
  (yield 2)
  (yield 3))

(define t (test-gen))
(display (t)) (newline)
(display (t)) (newline)
(display (t)) (newline)
(display (t)) (newline)


Output:
1
2
3
4
1
2
3
test-gen: unexpected return


Create a new paste based on this one


Comments: