在公共Lisp中使用循环宏嵌套循环 [英] Nested Loops Using Loop Macro in Common Lisp
问题描述
我正在尝试在CL中实现一个基本的嵌套循环,但是Loop宏正在抵抗这种情况.基本上,我想找到所有可能的3位数字的乘积并将它们累加到一个列表中.
I am trying to implement a basic nested loop in CL, but the Loop macro is resisting this. Basically, I would like to find all possible products of 3-digit numbers and accumulate them into a list.
这是我的尝试:
(loop for x downfrom 999 to 998 do (loop for y downfrom 999 to 998 collect (* x y)))
以上代码出于某种原因返回 NIL
.顺便说一句,我意识到我只用到998,但这是出于测试目的.
The code above returns NIL
for some reason. By the way, I realize that I only run down to 998, but this is done for testing purposes.
我该怎么做才能获得这样的列表:
What could I do to obtain a list like this:
(999 * 999 999 * 998 ... 998 * 998 998 * 997 ... 997 * 997 997 * 996 ... 100 * 100)
(999*999 999*998 ... 998*998 998*997 ... 997*997 997*996 ... 100*100)
推荐答案
内部循环中的 COLLECT
子句不影响外部循环.因此,内部循环返回结果列表,但是外部循环中的 DO
-子句只是丢弃结果.您应该使用 APPEND
或 NCONC
而不是 DO
.通常,即使没有性能问题,最好还是坚持使用 APPEND
,即使在这种情况下 NCONC
是安全的.
The COLLECT
-clause in the inner loop doesn't affect the outer loop. So the inner loop returns a list of results, but the DO
-clause in the outer loop just discards the result. You should use APPEND
or NCONC
instead of DO
. Usually it's better to just stick with APPEND
if there are no performance concerns, even if in this case NCONC
would be safe.
(loop for x downfrom 999 to 900
append (loop for y downfrom 999 to 900
collect (* x y)))
这篇关于在公共Lisp中使用循环宏嵌套循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!