If you have to do it over and over again on the same list,
tail-wagging
might be the best solution (which I learned from Edi Weitz's book):
(defparameter *l* (list 'a 'b 'c 'd 'e 'f))
give the last cons-cell of *l*
a name
(defparameter *tail* (last *l*))
now, (cdr *tail*)
is the last element of the list: '()
.
let's say you want to add (list 'g 'h 'i)
to its end.
assign (setf
) it to (cdr *tail*)
which is the last cons
-cell: '()
of the list *l*
,
and reassign (setf
) the new last cons element to tail.
(setf (cdr *tail*) (list 'g 'h 'i)
*tail* (last *tail*))
now, *l*
is mutated to contain the second list.
and *tail*
names the last cons
cell of this new list.
*l*
;; (a b c d e f g h i)
*tail*
;; (i)
The next time, when *tail*
has to be extended by a list, you don't have to traverse all the list again, but can just assign to cdr
of *tail*
the to-be-appended-list and then the original list will be modified.
by the way, I stumbled over tail-wagging
when contemplating over tailp