iterating through the same list with two indices
Posted: Thu Mar 01, 2012 10:55 am
I need to run through a list comparing each member to every member after that member for a condition. A very naiive approach would be:
This is easily understood, but very ugly.
Another lispier, but probably just as ugly, way would be
Is there a cleaner way to do this?
Edit, after some more thinking, this:
Code: Select all
(loop for i from 0 to (1- (length THE-LIST)) do
(loop for j from (1+ i) to (1- (length THE-LIST)) do
(test-the-items (nth i THE-LIST) (nth j THE-LIST))
Another lispier, but probably just as ugly, way would be
Code: Select all
(mapcar #'(lambda (item1)
(mapcar #'(lambda (item2)
(test-the-items item1 item2))
(nthcdr (position item1 THE-LIST)))) THE-LIST)
Edit, after some more thinking, this:
Code: Select all
(loop for i in THE-LIST do
(loop for j in (nthcdr (1+ (position i THE-LIST)) THE-LIST) do
(test-the-items i j))