Sometime, I need to iterate $n$ times where $n$ is the number of elements in a list. Of course, I could write something like:
(loop for i from 0 below (list-length l)
do something)
But I like to write rather:
(loop for i from 0
for u in l ; unused 'u' variable
do something)
where the for u in l
part is merely intended to stop the loop after $n$ iterations. But then I don't use the u
variable, and the interpreter keeps complaining. Is there some way to handle this style of coding? Should I avoid it and use list-length
instead?
CodePudding user response:
(loop for i from 0
for NIL in l
do something)
NIL should do it.
The LOOP destructuring pattern can be empty and the rest list elements are ignored. Additionally: In a LOOP destructuring pattern, NIL indicates that the variable is not used.
CodePudding user response:
Try the repeat
clause:
(loop repeat (length l) ...)
The argument expression of the repeat
clause is required to be evaluated once.
CodePudding user response:
One horrible hack to do this which does not involve any extra traversals and if you really need to use loop
is:
(defun foo (l)
(loop for i upfrom 0
for u = l then (cdr u)
while (consp u)
collect i))
But probably Kaz's answer of (loop repeat (length l) ...)
is fine in practice, if you must use loop
.