Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Basic while loop equipped with break #20

Open
countvajhula opened this issue Sep 1, 2021 · 0 comments
Open

Basic while loop equipped with break #20

countvajhula opened this issue Sep 1, 2021 · 0 comments

Comments

@countvajhula
Copy link

Macro

(define-syntax-parameter break
  (lambda (stx)
    (raise-syntax-error (syntax-e stx) "can only be used inside `while`")))

(define-syntax-parse-rule (while condition body ...)
  (call/ec
   (λ (return)
     (syntax-parameterize ([break (make-rename-transformer #'return)])
       (let loop ()
         (when condition
           (begin body ...
                  (loop))))))))

This uses an escape continuation to provide the semantics of break, and leverages it using a syntax parameter so that the continuation is accessible in the lexical scope of the while body, and also so that break is a syntax error outside the while loop.

Example

(define x 5)
(while (> x 0)
  (displayln x)
  (set! x (sub1 x)))

(set! x 5)
(while #t
  (displayln x)
  (set! x (sub1 x))
  (unless (> x 0)
    (break)))

Licence

This code and all associated text involved in this submission is released as public domain.

bennn added a commit to syntax-objects/syntax-parse-example that referenced this issue Oct 11, 2021
bennn added a commit to syntax-objects/syntax-parse-example that referenced this issue Oct 27, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant