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
defstruct pointgivesxandya0.0default and a:type single-float.make-pointtakes keyword arguments per slot, so*start*keeps every default.copy-pointclones*target*, and(setf (point-x *shifted*) 6.0)writes through an accessor.
Keywords and builtins used here
defstructdefundefvarexptformatsetfsqrt
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.
Step 1 of 3 in Structures & CLOS, step 19 of 27 in Language basics.