gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:01:12 26 4
gpt4 key购买 nike

以下 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com