defclass in Lisp
A CLOS class spells out each slot's :initarg, :accessor, and :initform by hand.
;; Shape classes with initargs, accessors, and initform defaults.
(defclass shape ()
((name :initarg :name :accessor shape-name :initform "shape")
(sides :initarg :sides :accessor shape-sides :initform 0)))
(defclass rectangle (shape)
((width :initarg :width :accessor rectangle-width :initform 1)
(height :initarg :height :accessor rectangle-height :initform 1)))
(defvar *card* (make-instance 'rectangle :name "index card"
:sides 4 :width 5 :height 3))
(setf (rectangle-height *card*) 4)
(format t "~a has ~d sides and area ~d~%"
(shape-name *card*) (shape-sides *card*)
(* (rectangle-width *card*) (rectangle-height *card*)))
How it works
shapenames two slots;rectangleinherits them and addswidthandheight.make-instancepasses:name,:sides,:width, and:heightas initargs.- Accessors read and write:
(setf (rectangle-height *card*) 4)updates the slot in place.
Keywords and builtins used here
defclassdefvarformatsetf
The run, in numbers
- Lines
- 18
- Characters to type
- 633
- Tokens
- 102
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 87 seconds.
Step 2 of 3 in Structures & CLOS, step 20 of 27 in Language basics.