Structures


1. Simple Case: (defstruct Name Slot1 Slot2 Slot3...)

E.g.

(defstruct Submarine Course Speed Depth)

This creates a function name make-Submarine that accepts initialization keywords :Course, :Speed, and :Depth. It also creates slot lookup functions Submarine-Course, Submarine-Speed, and Submarine-Depth, and slot setting functions (setf Submarine-Course), (setf Submarine-Speed) and (setf Submarine-Depth).


(setq Sub-1 (make-Submarine :Course 90 :Speed 5.5 :Depth 200)) 
(Submarine-Course Sub-1) ==> 90
(setf (Submarine-Course Sub-1) 270)
(Submarine-Course Sub-1) ==> 270
(type-of Sub-1) ==> SUBMARINE
(typep Sub-1 'Submarine) ==> T

2. Default Values to Slots: (defstruct Name (Slot1 Default-Val1) (Slot2 Default-Val2) ...)

(defstruct Submarine
  (Course 0)
  (Speed 5.0)
  (Depth 300))

(setq Sub-1 (make-Submarine :Speed 5.5 :Depth 200)) 
(Submarine-Course Sub-1) ==> 0
(Submarine-Speed Sub-1) ==> 5.5

There are also :type and :read-only slot specifiers that can be added.

3. Simple Inheritance: (defstruct (Name (:include Parent)) Slot-Descriptions)


(defstruct (Kilo (:include Submarine))
  (Class 'Kilo))
(setq Kilo-1 (make-Kilo :Speed 6.2 :Depth 150))
(Kilo-Class Kilo-1)==> KILO
(Kilo-Speed Kilo-1)==> 6.2
(Submarine-Speed Kilo-1)==> 6.2
(type-of Kilo-1)==> KILO
(typep Kilo-1 'Kilo)==> T
(typep Kilo-1 'Submarine)==> T

There is also a :conc-name argument that tells it what prefix to use for the slot names (the structure name is the default), which allows a value of NIL to mean "no prefix". However, structures are best reserved for simple applications. In more complex areas the far greater power and flexibility of CLOS is more appropriate.