问题描述
我正在尝试在 CL 中实现一个基本的嵌套循环,但 Loop 宏拒绝这样做.基本上,我想找出所有可能的三位数的乘积并将它们累加到一个列表中.
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)
推荐答案
内循环中的 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)))
这篇关于在 Common Lisp 中使用循环宏的嵌套循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!