common-lisp - Common Lisp 的 "loop for"宏如何与多个 "and"ed 计数器一起工作?

标签 common-lisp

以下 Common Lisp 代码不会产生我期望的输出:

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

使用 SCBL,它会产生以下输出:
5 5
6 5
7 6
8 7
9 8
10 9

我期望a和b的值在每一行都相同。

在这种情况下,我在网上搜索了关于循环宏的良好文档,但找不到太多。我很感激任何见解!

最佳答案

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

可以看出上面的代码在概念上接近 PSETF 。值以“并行”更新。原因是AND。

让我们用 FOR 替换 AND:
(loop for a from 5 to 10
      for b = a
      do (format t "~d ~d~%" a b))

上面将更新概念上接近于通常的 SETF 的变量,“顺序地”。
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

有关解释,请参阅 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*.

关于common-lisp - Common Lisp 的 "loop for"宏如何与多个 "and"ed 计数器一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4230960/

相关文章:

c - 如何从对 ffi :c-inline in ecl? 的调用中返回字符串

common-lisp - Common Lisp 多个元类

lisp - 添加两个列表

validation - LISP - 检查罗马数字转换器的有效罗马数字

lisp - '(a b c) and (list ' 和 'b ' c) 有什么区别?

lisp - 理解 Common Lisp 中的函数 `tailp`

common-lisp - 在 SBCL 内部使用 deftransform/defknown 使编译器转换用户编写的函数

lisp - 在 Common Lisp 和 Let 中修改哈希表

format - CL 格式配方 : Dealing with nil as a value

lisp - 来自宏的函数调用的参数评估