Next: Continuations, Previous: and or, Up: Control Mechanisms
Scheme has only few iteration mechanisms, mainly because iteration in
Scheme programs is normally expressed using recursion. Nevertheless,
R5RS defines a construct for programming loops, calling do. In
addition, Guile has an explicit looping syntax called while.
The init expressions are evaluated and the variables are bound to their values. Then looping starts with testing the test expression. If test evaluates to a true value, the expr following the test are evaluated and the value of the last expr is returned as the value of the
doexpression. If test evaluates to false, the commands are evaluated in order, the steps are evaluated and stored into the variables and the next iteration starts.Any of the step expressions may be omitted, so that the corresponding variable is not changed during looping.
Evaluate all expressions in body in order, as long as cond evaluates to a true value. The cond expression is tested before every iteration, so that the body is not evaluated at all if cond is
#fright from the start. Within body, you can use:(continue) to skip the rest of the body and jump to beginning (break [val]) to exit the body, returning val (or #t if not specified)If no
breakclause is evaluated, the value ofwhileis #t.
Named let is a variant of let which creates a procedure and calls
it in one step. Because of the newly created procedure, named let is
more powerful than do–it can be used for iteration, but also
for arbitrary recursion.
For the definition of bindings see the documentation about
let(see Local Bindings).Named
letworks as follows:
- A new procedure which accepts as many arguments as are in bindings is created and bound locally (using
let) to variable. The new procedure's formal argument names are the name of the variables.- The body expressions are inserted into the newly created procedure.
- The procedure is called with the init expressions as the formal arguments.
The next example implements a loop which iterates (by recursion) 1000 times.
(let lp ((x 1000)) (if (positive? x) (lp (- x 1)) x)) ⇒ 0