typestar

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

  1. ~a prints for people, ~d takes an integer, and ~,2f rounds a float to two places.
  2. ~{~a~^, ~} walks a list, with ~^ dropping the separator after the last item.
  3. ~:p pluralizes from the preceding argument and ~r spells a number out in words.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Format & macros, step 22 of 27 in Language basics.

← Previous Next →