syntax-objects / Summer2021

Syntax Parse Bee 2021
11 stars 3 forks source link

Basic while loop equipped with break #20

Open countvajhula opened 3 years ago

countvajhula commented 3 years ago

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.