Building lists in Lisp
Growing a playlist with push, then straightening it out with reverse and append.
;; push grows a list at the front, so the additions come out backward
(defparameter *playlist* (list "aja" "deacon blues"))
(push "peg" *playlist*)
(push "home at last" *playlist*)
;; reverse undoes that order and append joins on a closing track
(defparameter *encore* (append (reverse *playlist*) (list "josie")))
(defun announce (tracks)
(format t "~a tracks, opening with ~a~%" (length tracks) (first tracks))
(dolist (track tracks)
(format t " - ~a~%" track)))
(announce *encore*)
How it works
- Each
pushadds to the front of*playlist*, so the tracks stack up in reverse. (append (reverse *playlist*) (list "josie"))restores the order and adds a closing track.announcereportslengthandfirst, then walks the whole list withdolist.
Keywords and builtins used here
appenddefparameterdefundolistfirstformatlengthlistpushreverse
The run, in numbers
- Lines
- 14
- Characters to type
- 488
- Tokens
- 73
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 58 seconds.
Step 2 of 3 in Lists & conses, step 5 of 27 in Language basics.