3 ms·
Another common pattern is to keep track of the last cons and add there. This saves the reverse operation. (loop for i in some-list when (evenp i) collect i) wi
by lispm 3y ago
Another common pattern is to keep track of the last cons and add there. This saves the reverse operation. (loop for i in some-list when (evenp i) collect i) will do something like that behind the scenes.
- brabel 3y agoI don't understand how that works. (reverse) changes every cons cell in order to make each cell point in the "opposite" direction. Do you have a reference I can check?
- lispm 3y agoImagine, we want to write a function which returns a list of numbers from 0 below N. This is just an illustration of the iteration principles. One could use a numeric loop, push each number to the front and return the reversed result list: (defun iota (n &aux result) (dotimes (i n (nreverse result)) (push i result))) But we can also use: (defun iota (n &aux (result (list nil)) (pointer result)) (dotimes (i n (cdr result)) (setf (cdr pointer) (list i) pointer (cdr pointer)))) As you can see, there is no REVERSE needed. Instead the pointer is moved to mark the cons where to add the next cons+item.
- brabel 3y agoOh I see. You keep track of the last cons * on each iteration * :) (this last bit was missing). Interesting, thanks for showing it.