typestar

defun & docstrings in Lisp

Defines a hiking-pace function whose docstring travels with it, then calls it with and without the optional argument.

;; DEFUN binds a name to a function; the string after the lambda list
;; is a docstring the environment can hand back, not a comment.
(defun hike-hours (miles &optional (pace 2.5))
  "Return the hours needed to walk MILES at PACE miles per hour."
  (/ miles pace))

;; An &optional argument may be left out, and then takes its default.
(defvar *loop-trail* (hike-hours 12))
(defvar *steep-trail* (hike-hours 12 1.5))

(format t "loop trail:  ~,1f hours~%" *loop-trail*)
(format t "steep trail: ~,1f hours~%" *steep-trail*)
(format t "docstring: ~a~%" (documentation 'hike-hours 'function))

How it works

  1. (defun hike-hours (miles &optional (pace 2.5)) names the function and gives pace a default.
  2. The string on the next line is a docstring, which (documentation 'hike-hours 'function) reads back.
  3. (hike-hours 12) takes the default pace while (hike-hours 12 1.5) supplies its own.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
585
Tokens
60
Three-star pace
80 tpm

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

Type this snippet

Step 1 of 3 in Functions, step 10 of 27 in Language basics.

← Previous Next →