;; The first three lines of this file were inserted by DrScheme. They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "reader.ss" "plai" "lang") ; Scheme has no while loop built in. Say that we want to create one ; of the form ; ; ::= '(' 'while' ')' ; ; i.e., (while ) ; ; That expands into: ; ; (letrec ([loop (λ () ; (if ; (begin (loop)) ; (void)))]) ; (loop))) ; ; We create this by defining a "macro", or "new syntax rule" for ; the language. What we're really making is a little procedure that ; acts as a plugin for the Scheme interpreter. This saves us the work ; of writing our own interpreter just to make one small change from ; basic Scheme. The Scheme syntax for this is remarkably elegant... ; it looks just like the specification above: ; (while ) (define-syntax-rule (while ) (letrec ([loop (λ () (if (begin (loop)) (void)))]) (loop))) ; Here's an example of it in action: (define x 1) (while (< x 5) (begin (display x) (set! x (+ x 1)))) (display x) ; Note: Scheme has something called "named let" that is a ; shorthand for creating a loop procedure and then running ; it recursively. But let's just stick to the minimal ; Scheme features that we already know.