List Manipulation
(defparameter *list* 0 :one "two" (make-hash-table) 'three)
;; first (car), second, third, tenth ... (nth n list)
(first *list*)
;; rest (cdr)
(rest *list*)
(rest '(1 2 3)) = (2 3)
;; last, butlast
(last '(1 2 3)) = (3)
(first (last *list*))
(alexandria:last-elt *list*)
(butlast *list*)
(butlast '(1 2 3)) = (1 2)
(nthcdr 2 *list*)
Add elements to a list, set elements.
(defparameter *my-list* (list 0 1 2))
(push :thing *my-list*) ;; push at the first place
(pop *my-list*) ;; take at the first place
(pushnew :thing *my-list*) ;; will only push a new element if it doesn't exist
(list* arg &rest others)
(list* :thing *my-list*)
;; add a few elements in front of a list
;; typical idiom: push + reverse
;; instead of appending to the end.
(let ((list (list)))
(dotimes (i 10)
(push i list))
(reverse list))
(loop :for i :upto 10 :collect i)
;; set elements of a list
(setf (nth 1 *list*) :changed!)
(append (list 1 2 3) (list 10 20 30))
(concatenate 'list (list 1 2 3) (list 10 20 30))
Using QUOTE is not the same as LIST function
DANGER: when you think that using QUOTE as in '(1 2 3) is like creating a list with the LIST function
'(1 2 3) is not like (list 1 2 3)
(defun supposedly-constant-data ()
;; DON'T
'(1 2 3))
;; sometmes later...
(setf (first (supposedly-constant-data)) 99)
;; we do not have constant data, it does not create a new list but references the same one
(defun constant-data ()
(list 1 2 3))
;; ^^ fresh list constructor
(setf (first (constant-data)) 99) ;; OK!
;; ^^ fresh list