A Scheme “while loop”

October 15, 2009
by Lee Spector (lspector)

There was a question in class about whether Scheme has an iteration construct like the “while loops” of other languages, in which there is a condition and a body and the body is executed repeatedly until the condition becomes false. I showed how to do this using “do”, but noted that it was a little awkward because you have to specify an empty variable list, the negation of the condition, etc. I also said that one could define a syntax transformation that would give you a real, more natural “while.” Here’s a version of what I was talking about:

(define-syntax (while stx)
  (syntax-case stx ()
      ((_ condition expression ...)
       #`(do ()
           ((not condition))
           expression
           ...))))

If you haven’t previously seen “define-syntax” then this will look quite odd, but you can use it without understanding it. Just include it in your code and then you can do something like this:

(define x 0)

(while (< x 5)
       (printf "~A\n" x)
       (set! x (+ x 1)))

That will print:

0
1
2
3
4

The first thing after “while” is the condition. It will be evaluated and if it is true (producing anything other than #f) then everything else in the expression will be evaluated. Then the condition will be evaluated again and, if it is true, it everything else in the expression will be evaluated again. And so on, until the condition evaluates to false (#f), at which point the whole “while” expression will be done (and won’t return anything).



One Response to “A Scheme “while loop””

  1.   Code Immersion » Blog Archive » Animating several things at once Says:

    […] A Scheme “while loop” […]

Leave a Reply

You must be logged in to post a comment.