typestar

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

  1. Each push adds to the front of *playlist*, so the tracks stack up in reverse.
  2. (append (reverse *playlist*) (list "josie")) restores the order and adds a closing track.
  3. announce reports length and first, then walks the whole list with dolist.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Lists & conses, step 5 of 27 in Language basics.

← Previous Next →

Building lists in other languages