Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Common Lisp's "loop for" macro work with multiple "and"ed counters?

Tags:

common-lisp

The following Common Lisp code does not produce the output I would expect it to:

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

Using SCBL, it produces this output:

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

I was expecting the values of a and b to be the same on each line.

I have searched the web for good documentation of the loop macro in this instance but couldn't find much. I'd appreciate any insight!

like image 980
presto8 Avatar asked Dec 07 '22 00:12

presto8


1 Answers

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

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

Let's replace AND with FOR:

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

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

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

For an explanation see the Common Lisp HyperSpec 6.1.2.1 Iteration Control:

If multiple iteration clauses are used to control iteration, variable initialization and stepping occur sequentially by default. The and construct can be used to connect two or more iteration clauses when sequential binding and stepping are not necessary. The iteration behavior of clauses joined by and is analogous to the behavior of the macro do with respect to do*.

like image 156
Rainer Joswig Avatar answered May 24 '23 19:05

Rainer Joswig