开发者

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

The following Common Lisp code does not produce the output I would e开发者_StackOverflow中文版xpect 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!


(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*.


Step forms of AND clauses are evaluated prior to any of the variables being given their new values. Use for b = a then a instead to force in-order evaluation.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜