The general Lisp loop can be used very nicely for this, as in the following two examples. The first example loop for (xyz) in the list. However, the default step is cdr ( rest ), so if the list is (1 2 3 4 5) , you will get (1 2 3) , (2 3 4) , etc. For (xyz) .
CL-USER> (loop for (xyz) on '(1 2 3 4 5 6 7 8 9 10 11 12) do (print (list zyx))) (3 2 1) (4 3 2) (5 4 3) (6 5 4) (7 6 5) (8 7 6) (9 8 7) (10 9 8) (11 10 9) (12 11 10) (NIL 12 11) (NIL NIL 12) NIL
If you do not need overlap between iterations, specify that the step function is something that moves further down the list. For example, if you pull three elements at a time, use cdddr :
CL-USER> (loop for (xyz) on '(1 2 3 4 5 6 7 8 9 10 11 12) by 'cdddr do (print (list zyx))) (3 2 1) (6 5 4) (9 8 7) (12 11 10) NIL
Implementing a section using this method
Another answer implements a copy of each_slice using a helper function. However, note that partition (in this sense) is simply each_slice with an identity function. This suggests that we should be able to implement it using the above idiom. Anonymous function
(lambda (list) (nthcdr n list))
- required step function. Since we do not know how many elements cells have before runtime, we cannot bind each element, as we did above, using (xyz) . We need to match each tail of the list when we leave and retrieve the elements of n subsequences. This is where the partition based loop is executed.
CL-USER> (defun partition (list cell-size) (loop for cell on list by
source share