by ColonelPhantom · 2y ago · 0 comments
Appending to a linked list is fine if you can mutate and keep a pointer to the tail, but then again, extending mutable arrays is also amortized O(1) assuming a reasonable allocation scheme.
Check this program as an example: http://www.norvig.com/java-lisp.html
Recursion is done with `(cons (nth-digit digits start) words)` and recursion ends with `(format t "~a:~{ ~a~}~%" num (reverse words))`.
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.