typestar

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

  1. shape names two slots; rectangle inherits them and adds width and height.
  2. make-instance passes :name, :sides, :width, and :height as initargs.
  3. Accessors read and write: (setf (rectangle-height *card*) 4) updates the slot in place.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Structures & CLOS, step 20 of 27 in Language basics.

← Previous Next →