Alists & plists in Lisp
Looks up an area code in an association list and a field in a property list, and says when each shape fits.
;; An association list is a list of key/value conses, and ASSOC hands
;; back the first pair whose key matches.
(defvar *area-codes*
'((503 . "Portland") (206 . "Seattle") (415 . "San Francisco")))
(defvar *city* (cdr (assoc 206 *area-codes*)))
(defvar *missing* (assoc 999 *area-codes*))
;; A property list is a flat run of alternating keys and values that
;; GETF reads. Plists suit small records with fixed fields; alists
;; suit longer tables and keys that are not keywords.
(defvar *book* (list :title "Dune" :year 1965 :pages 412))
(defvar *year* (getf *book* :year))
(defvar *edition* (getf *book* :edition "first"))
(format t "206 is ~a, 999 is ~a~%" *city* *missing*)
(format t "~a (~a), ~a edition~%" (getf *book* :title) *year* *edition*)
How it works
(assoc 206 *area-codes*)returns the matching cons, socdrgets the city and a miss returns nil.(list :title "Dune" :year 1965 :pages 412)is a flat plist that(getf *book* :year)reads.(getf *book* :edition "first")takes a default, and the comment contrasts fixed records with longer tables.
Keywords and builtins used here
assoccdrdefvarformatgetflist
The run, in numbers
- Lines
- 17
- Characters to type
- 752
- Tokens
- 99
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 85 seconds.
Step 2 of 3 in Collections, step 17 of 27 in Language basics.