简体   繁体   English

在公共Lisp中使用循环宏嵌套循环

[英]Nested Loops Using Loop Macro in Common Lisp

I am trying to implement a basic nested loop in CL, but the Loop macro is resisting this. 我正在尝试在CL中实现一个基本的嵌套循环,但是Loop宏正在抵抗这种情况。 Basically, I would like to find all possible products of 3-digit numbers and accumulate them into a list. 基本上,我想找到所有可能的3位数字的乘积并将它们累加到一个列表中。

Here is my attempt: 这是我的尝试:

 (loop for x downfrom 999 to 998 do (loop for y downfrom 999 to 998 collect (* x y)))

The code above returns NIL for some reason. 上面的代码出于某些原因返回NIL By the way, I realize that I only run down to 998, but this is done for testing purposes. 顺便说一句,我意识到我只用到998,但这是出于测试目的。

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)

The COLLECT -clause in the inner loop doesn't affect the outer loop. 内循环中的COLLECT子句不影响外循环。 So the inner loop returns a list of results, but the DO -clause in the outer loop just discards the result. 因此,内部循环返回结果列表,但是外部循环中的DO子句只是丢弃结果。 You should use APPEND or NCONC instead of DO . 您应该使用APPENDNCONC而不是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. 通常,即使没有性能问题,最好还是坚持使用APPEND ,即使在这种情况下NCONC也是安全的。

(loop for x downfrom 999 to 900
      append (loop for y downfrom 999 to 900
                   collect (* x y)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM