3 ms·
Imagine, 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
by lispm 3y ago
Imagine, 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.