How does the general Lisp macro loop work with multiple and counters?

The following general Lisp code does not output the result I would expect from it:

(loop for a from 5 to 10 and b = a do (format t "~d ~d~%" ab)) 

Using SCBL, he produces this output:

 5 5 6 5 7 6 8 7 9 8 10 9 

I expected the values ​​of a and b to be the same on every line.

I searched the web for good documentation on loop macro in this instance, but couldn't find much. I would be grateful for your understanding!

+4
source share
2 answers
 (loop for a from 5 to 10 and b = a do (format t "~d ~d~%" ab)) 

Above the code can be seen conceptually close to the PSETF. Values ​​are updated in 'parallel'. The reason is that AND.

Replace AND with FOR:

 (loop for a from 5 to 10 for b = a do (format t "~d ~d~%" ab)) 

Above, it will update variables conceptually close to the usual SETF, sequentially.

 CL-USER 20 > (loop for a from 5 to 10 for b = a do (format t "~d ~d~%" ab)) 5 5 6 6 7 7 8 8 9 9 10 10 

For an explanation, see Common Lisp HyperSpec 6.1.2.1 Iterative Control :

If multiple iteration clauses are used to control iteration, the default initialization and stepping variable. And the design can be used to connect two or more iterative articles when sequential linking and stepping is not necessary. Iterative behavior related to and similar to macro behavior with respect to do *.

+11
source

The step forms of AND clauses are evaluated before any of the variables gets its new values. Use for b = a then a instead to force the order to be evaluated.

Ref. http://www.gigamonkeys.com/book/loop-for-black-belts.html#equals-then-iteration

+3
source

All Articles