如何在嵌套循环中模拟收集
How to simulate collecting in nested loop for
我想创建一个 (a . b)
对 1 < a < b <= n
到 n
的列表,例如n = 5
:
((2 . 3) (2 . 4) (3 . 4) (2 . 5) (3 . 5) (4 . 5))
(对的顺序并不重要。)
我想出了代码
(defun create-pairs (upper-bound)
(loop for i from 3 to upper-bound
for j from 2 to (1- upper-bound)
collecting (cons j i)))
但这并不符合我的要求
* (create-pairs 5)
((2 . 3) (3 . 4) (4 . 5))
因为循环同时递增。
因此我尝试了这个
(defun create-pairs (upper-bound)
(loop for i from 3 to upper-bound do
(loop for j from 2 to (1- upper-bound)
collecting (cons j i))))
结果:
* (create-pairs 5)
NIL
我不记得在哪里,但我读到不能像我第二次尝试那样在结构中使用 collecting
。
那么如何得到我想要的结果呢?用loop for
不就可以解决吗?
你快到了 - 你只需要 accumulate the results of the inner loop
:
(defun create-pairs (upper-bound)
(loop for i from 3 to upper-bound nconc
(loop for j from 2 below i
collect (cons j i))))
(create-pairs 5)
==> ((2 . 3) (2 . 4) (3 . 4) (2 . 5) (3 . 5) (4 . 5))
我想创建一个 (a . b)
对 1 < a < b <= n
到 n
的列表,例如n = 5
:
((2 . 3) (2 . 4) (3 . 4) (2 . 5) (3 . 5) (4 . 5))
(对的顺序并不重要。)
我想出了代码
(defun create-pairs (upper-bound)
(loop for i from 3 to upper-bound
for j from 2 to (1- upper-bound)
collecting (cons j i)))
但这并不符合我的要求
* (create-pairs 5)
((2 . 3) (3 . 4) (4 . 5))
因为循环同时递增。
因此我尝试了这个
(defun create-pairs (upper-bound)
(loop for i from 3 to upper-bound do
(loop for j from 2 to (1- upper-bound)
collecting (cons j i))))
结果:
* (create-pairs 5)
NIL
我不记得在哪里,但我读到不能像我第二次尝试那样在结构中使用 collecting
。
那么如何得到我想要的结果呢?用loop for
不就可以解决吗?
你快到了 - 你只需要 accumulate the results of the inner loop
:
(defun create-pairs (upper-bound)
(loop for i from 3 to upper-bound nconc
(loop for j from 2 below i
collect (cons j i))))
(create-pairs 5)
==> ((2 . 3) (2 . 4) (3 . 4) (2 . 5) (3 . 5) (4 . 5))