(guile.info.gz) while do
Info Catalog
(guile.info.gz) and or
(guile.info.gz) Control Mechanisms
(guile.info.gz) Continuations
26.4 Iteration 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'.
-- syntax: do ((variable1 init1 step1) ...) (test expr ...) command ...
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 `do' expression. 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.
-- syntax: while cond body ...
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 `#f' right from the start.
Another very common way of expressing iteration in Scheme programs is
the use of the so-called "named let".
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.
-- syntax: let variable bindings body
For the definition of BINDINGS see the documentation about `let'
( Local Bindings).
Named `let' works 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
Info Catalog
(guile.info.gz) and or
(guile.info.gz) Control Mechanisms
(guile.info.gz) Continuations
automatically generated byinfo2html