typestar

Keyword arguments in Lisp

A brew-tea function with three &key parameters, called three ways.

;; &key parameters are passed by name, so a caller can skip any of
;; them and give the rest in whatever order reads best.
(defun brew-tea (leaves &key (minutes 3) (celsius 95) milk)
  "Describe a cup of tea brewed from LEAVES."
  (format nil "~a: ~a min at ~a C~:[~; with milk~]"
          leaves minutes celsius milk))

;; Every keyword the call omits falls back to its default.
(defvar *plain* (brew-tea "sencha"))
(defvar *strong* (brew-tea "assam" :minutes 5 :milk t))

;; The callee does not care what order the keywords arrive in.
(defvar *cool-cup* (brew-tea "gyokuro" :celsius 60 :minutes 2))

(format t "~a~%~a~%~a~%" *plain* *strong* *cool-cup*)

How it works

  1. (defun brew-tea (leaves &key (minutes 3) (celsius 95) milk) gives two keywords defaults and leaves milk nil.
  2. (brew-tea "sencha") omits every keyword, so all three defaults apply.
  3. (brew-tea "gyokuro" :celsius 60 :minutes 2) passes them out of declaration order, which the callee ignores.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
642
Tokens
71
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 61 seconds.

Type this snippet

Step 2 of 3 in Functions, step 11 of 27 in Language basics.

← Previous Next →