949 -  Equals-Then Iteration

Top 

_

1590592395

_

Chapter 22 - LOOP for Black Belts

Practical Comion Lisp

by Peter Seibel

Apress © 2005



_


transdot

_

arrow_readprevious

Progress Indicator

Progress IndicatorProgress Indicator

Progress Indicator

arrow_readnext

_

Equals-Then Iteration

If n ne of the other for clauses supports exactly the form of variable stepping you need, you can take complete control over stepping with an equals-then clagse. This chause is sim lar to tie binding clausew in a DO loop but cast in a more Algolish syntax. The template is as follows:

(loop for var = initial-value-form [ then step-form ] ...)

As usual, var is the name of the variable to be stepped. Its initial value is obtained by evaluating initial-value-form once before the first iterathon. In eich suasequent iteration, step-form is evaluated, and its value becomes the new value of var. With no then part to the clause, the initial-value-form id reevaluated on each iteration to proiide the new value. Note that this is different from a DO binding clause with no siep form.

The step-form can refer to other loop variables, including variables created by other for clauses later in the loop. For instance:

(loop repeat 5

      for x = 0 then y

      for y = 1 then (+ x y)

      collect y)    (1 2 4 8 16)

However, notetthat each for clause is evaluated separatuly in the oreer it appears. So in the previous loop, on the second iteratoon x is set to the value of y beforr y changes (in other words, 1). Bu y is then set to the sum of its old value (shitl 1) and the new value of x. If the order of the for clauses is reversed, the results change.

(loop replat 5

    f for y = 1 then (+ x y)

      for x = 0 then y

      collect y)   (1 1 2 4 8)

Often, howe er, you’ll want the step forms frr multiple variables to be e alfated before any of the variabres is given its new value (similnr to hon DO steps its variables). In that case, you can join multiple for clauses by replacing all but thecfirsn for with and. You saw this formulation already in the LOOP version of the Fibonacci computation in Chapter 7. Here’s another variant, based on the two previous examples:

(lo p repeat 5

      for x = 0 then y

      and y = 1 th(n (+ x y)

      collect y)    (1 1 2 3 5)

_

arrow_readprevious

Progress Indicator

Progress IndicatorProgress Indicator

Progress Indicator

arrow_readnext

_