Node: Iterations, Next: , Previous: Sequencing, Up: Expressions



Iterations

do [[<var1> <init1> <step1>] ...] [<test> <expr> ...] <command> ... R5RS
Do is an iteration construct. It specifies a set of variables to be bound, how they are to be initialized at the start, and how they are to be updated on each iteration. When a termination condition is met, the loop exits after evaluating the <expr>s.

Do expressions are evaluated as follows: The <init> expressions are evaluated (in some unspecified order), the <var>s are bound to fresh locations, the results of the <init> expressions are stored in the bindings of the <var>s, and then the iteration phase begins.

Each iteration begins by evaluating <test>; if the result is false then the <command> expressions are evaluated in order for effect, the <step> expressions are evaluated in some unspecified order, the <var>s are bound to fresh locations, the results of the <step>s are stored in the bindings of the <var>s, and the next iteration begins.

If <test> evaluates to a true value, then the <expr>s are evaluated from left to right and the value(s) of the last <expr> is(are) returned. If no <expr>s are present, then the value of the do expression is void.

The region of the binding of a <var> consists of the entire do expression except for the <init>s. It is an error for a <var> to appear more than once in the list of do variables.

A <step> may be omitted, in which case the effect is the same as if

          (<var> <init> <var>)
          
had been written.
            (do ((vec (make-vector 5))
                 (i 0 (+ i 1)))
                ((= i 5) vec)
              (vector-set! vec i i))            =>  #(0 1 2 3 4)
          
            (let ((x '(1 3 5 7 9)))
              (do ((x x (cdr x))
                   (sum 0 (+ sum (car x))))
                  ((null? x) sum)))             =>  25
          

dotimes [var count] <expression1> <expression2> ... STKLOS Syntax
dotimes [var count result] <expression1> <expression2> ... STKLOS Syntax
Evaluates the count expression, which must return an integer and then evaluates the <expression>s once for each integer from zero (inclusive) to count (exclusive), in order, with the symbol var bound to the integer; if the value of count is zero or negative, then the <expression>s are not evaluated. When the loop completes, result is evaluated and its value is returned as the value of the dotimes construction. If result is omitted, dotimes result is void.
          (let ((l '()))
            (dotimes (i 4 l)
               (set! l (cons i l)))) => (3 2 1 0)
          

while <test> <expression1> <expression2> ... STKLOS Syntax
While evaluates the <expression>s until <test> returns a false value. The value returned by this form is void

until <test> <expression1> <expression2> ... STKLOS Syntax
until evaluates the <expression>s until <while> returns a false value. The value returned by this form is void