format directives in Lisp
format directives are a miniature language for assembling strings.
;; Format directives compose into a small string-building language.
(defvar *crew* (list "ada" "grace" "alan"))
(defvar *fuel* 128.4567)
;; ~a prints for people, ~d takes an integer, ~,2f rounds a float.
(defvar *status* (format nil "pilot ~a, ~d stop~:p, ~,2f liters"
(first *crew*) 3 *fuel*))
;; ~{...~} walks a list and ~^ drops the separator after the last item.
(defvar *roster* (format nil "~{~a~^, ~}" *crew*))
;; ~r spells a number out in English words.
(defvar *count* (format nil "~r crew member~:p aboard" (length *crew*)))
(format t "~a~%~a~%~a~%" *status* *roster* *count*)
How it works
~aprints for people,~dtakes an integer, and~,2frounds a float to two places.~{~a~^, ~}walks a list, with~^dropping the separator after the last item.~:ppluralizes from the preceding argument and~rspells a number out in words.
Keywords and builtins used here
defvarfirstformatlengthlist
The run, in numbers
- Lines
- 16
- Characters to type
- 591
- Tokens
- 65
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 60 seconds.
Step 1 of 3 in Format & macros, step 22 of 27 in Language basics.