Next: , Previous: , Up: Loop   [Contents][Index]


15.25.9 Variable Initializations

A local loop variable is one that exists only when the Loop Facility is invoked. At that time, the variables are declared and are initialized to some value. These local variables exist until loop iteration terminates, at which point they cease to exist. Implicitly variables are also established by iteration control clauses and the ‘into’ preposition of accumulation clauses.

with

The loop keyword ‘with’ designates a loop clause that allows you to declare and initialize variables that are local to a loop. The variables are initialized one time only; they can be initialized sequentially or in parallel.

Sequential Initialization

By default, the with construct initializes variables sequentially; that is, one variable is assigned a value before the next expression is evaluated.

Use sequential binding for making the initialization of some variables depend on the values of previously bound variables. For example, suppose you want to bind the variables a, b, and c in sequence:

(loop with a = 1
  with b = (+ a 2)
  with c = (+ b 3)
  with d = (+ c 4)
  return (list a b c d))

The execution of the preceding loop is equivalent to the execution of the following code:

(let* ((a 1)
       (b (+ a 2))
       (c (+ b 3))
       (d (+ c 4)))
  (block nil
    (tagbody
      next-loop (return (list a b c d))
                (go next-loop)
      end-loop)))

Parallel Initialization with “and”

However, by using the loop keyword ‘and’ to join several with clauses, you can force initializations to occur in parallel; that is, all of the specified expressions are evaluated, and the results are bound to the respective variables simultaneously.

If you are not depending on the value of previously bound variables for the initialization of other local variables, you can use parallel bindings as follows:

(loop with a = 1
   and b = 2
   and c = 3
   and d = 4
  return (list a b c d))

The execution of the preceding loop is equivalent to the execution of the following code:

(let ((a 1)
      (b 2)
      (c 3)
      (d 4))
  (block nil
    (tagbody
       next-loop (return (list a b c))
                 (go next-loop)
       end-loop)))

Next: Conditional Execution, Previous: Value Accumulation, Up: Loop   [Contents][Index]