[英]How to use dependent loop variables with `loop` macro in Common Lisp
Consider the following snippet of C
code; 考虑以下
C
代码片段; the actual values for M
and the content of arr
don't actually matter. M
的实际值和arr
的内容实际上并不重要。
int arr[M] = {...};
for (int i=0; i<M; ++i) {
for (int j=i+1; j<M; ++j) {
/* do something */
}
}
What would be the (idiomatic and efficient) Common Lisp analog using the loop
macro (or if loop
is not right tool, any other construct)? 使用
loop
宏(或者如果loop
不是正确的工具,则使用任何其他构造)的(惯用且有效的)Common Lisp模拟是什么?
I know that comparing array access and list access is not correct but could not come up with a better example. 我知道比较数组访问和列表访问是不正确的,但无法提出更好的示例。
One possibility I tried is the following: 我尝试过的一种可能性如下:
(defvar l '(1 2 ...))
(loop :for n :on l :do
(loop :for x :in (cdr n) :do
;; do something
))
But this seems rather clunky. 但这似乎很笨拙。
Please note, that other similar questions deal with ranges not with lists. 请注意,其他类似问题也涉及范围而不是列表。
Not sure what you actually want to compute, but I don't think it is clunky. 不知道您实际要计算什么,但我认为它并不笨重。
Example: 例:
CL-USER 6 > (loop for (head . tail) on '(1 2 3 4)
do (loop for item in tail
do (print (list head item))))
(1 2)
(1 3)
(1 4)
(2 3)
(2 4)
(3 4)
NIL
If you want to keep pairs based on some test: 如果您想根据一些测试来保持配对:
CL-USER 36 > (defun mapcan-pairs (fn list)
(loop for (head . tail) on list
nconc (loop for item in tail
nconc (funcall fn head item))))
MAPCAN-PAIRS
CL-USER 37 > (defun keep-pairs (test list)
(mapcan-pairs (lambda (a b)
(when (funcall test a b)
(list (cons a b))))
list))
KEEP-PAIRS
CL-USER 38 > (keep-pairs (lambda (a b)
(= 13 (+ a b)))
'(1 2 3 7 1 4 5 6 3 5 10 15 3))
((3 . 10) (7 . 6) (3 . 10) (10 . 3))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.