typestar

defparameter & defvar in Lisp

Two ways to make a global: defparameter overwrites, defvar backs off.

;; defparameter always assigns; defvar only sets a name that is unbound
(defparameter *thermostat-target* 68)
(defvar *adjustments* 0)
(defvar *adjustments* 99)

;; earmuffs flag a special variable, visible inside every function below
(defun report-target ()
  (format t "target is ~a degrees~%" *thermostat-target*))

(defun bump-target (degrees)
  (setf *thermostat-target* (+ *thermostat-target* degrees))
  (incf *adjustments*))

(report-target)
(bump-target 4)
(report-target)
(format t "adjustments so far: ~a~%" *adjustments*)

How it works

  1. (defparameter *thermostat-target* 68) names a global; the second (defvar *adjustments* 99) is ignored because the name is already bound.
  2. Earmuffs mark both names special, so report-target and bump-target reach them without taking an argument.
  3. bump-target reassigns with setf and counts the call with incf.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
527
Tokens
65
Three-star pace
75 tpm

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

Type this snippet

Step 1 of 3 in Values & bindings, step 1 of 27 in Language basics.

Next →