typestar

defstruct in Lisp

defstruct declares a record and generates its constructor, accessors, and copier for free.

;; A point structure with typed slots, defaults, and generated helpers.

(defstruct point
  (x 0.0 :type single-float)
  (y 0.0 :type single-float)
  (label "origin"))

(defvar *start* (make-point))
(defvar *target* (make-point :x 3.0 :y 4.0 :label "target"))

(defun point-distance (a b)
  (sqrt (+ (expt (- (point-x b) (point-x a)) 2)
           (expt (- (point-y b) (point-y a)) 2))))

(defvar *shifted* (copy-point *target*))
(setf (point-x *shifted*) 6.0)

(format t "distance ~,2f, shifted x ~,1f~%"
        (point-distance *start* *target*) (point-x *shifted*))

How it works

  1. defstruct point gives x and y a 0.0 default and a :type single-float.
  2. make-point takes keyword arguments per slot, so *start* keeps every default.
  3. copy-point clones *target*, and (setf (point-x *shifted*) 6.0) writes through an accessor.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
541
Tokens
115
Three-star pace
75 tpm

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

Type this snippet

Step 1 of 3 in Structures & CLOS, step 19 of 27 in Language basics.

← Previous Next →