case dispatch in Lisp
case picks a branch by comparing one value against literal keys with eql.
;; case tests keys with eql, so the clauses stay bare symbols
(defun unit-label (measure)
(case measure
(celsius "degrees C")
(millibar "mb")
((meter meters) "m above sea level")
(otherwise "unrecognized unit")))
;; one clause can list several keys, and otherwise catches the rest
(defun log-reading (measure value)
(format t "~a ~a~%" value (unit-label measure)))
(log-reading 'celsius 21)
(log-reading 'millibar 1013)
(log-reading 'meters 348)
(log-reading 'furlong 2)
How it works
unit-labelmatches the symbolscelsiusandmillibarto their printed units.- The
((meter meters) "m above sea level")clause accepts either spelling of one key. otherwisecatches anything unlisted, which is what(log-reading 'furlong 2)hits.
Keywords and builtins used here
casedefunformat
The run, in numbers
- Lines
- 16
- Characters to type
- 472
- Tokens
- 70
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 52 seconds.
Step 2 of 3 in Control flow, step 8 of 27 in Language basics.