Structures and The Type System
type system
- visible
- extensible -- create new types at any time
TYPEP AND TYPE-OF
(typep 3 ’number) ⇒ t
(typep 3 ’integer) ⇒ t
(typep 3 ’float) ⇒ nil
(typep ’foo ’symbol) ⇒ t
(type-of 3.5) ⇒ short-float
(type-of ’(bat breath)) ⇒ cons
(type-of "Phooey") ⇒ (simple-string 6)
DEFINING STRUCTURES
(defstruct starship
(name nil)
(speed 0)
(condition ’green)
(shields ’down))
> (setf s2 ’#s(starship speed (warp 3)
condition red
shields up))
#S(STARSHIP NAME NIL
SPEED (WARP 3)
CONDITION RED
SHIELDS UP)
TYPE PREDICATES FOR STRUCTURES
(starship-p s2) ⇒ t
(typep s1 ’starship) ⇒ t
(type-of s2) ⇒ starship
ACCESSING AND MODIFYING STRUCTURES
When a new structure is defined, DEFSTRUCT creates accessor functions for each of its components
(starship-speed s2) ⇒ (warp 3)
(setf (starship-name s1) "Enterprise")
KEYWORD ARGUMENTS TO CONSTRUCTOR FUNCTIONS
> (setf s3 (make-starship :name "Reliant"
:shields ’damaged))
CHANGING STRUCTURE DEFINITIONS
Lisp Toolkit: DESCRIBE and INSPECT
> (describe ’fred)
FRED is an internal symbol in package USER.
> (describe s1)
#S(STARSHIP ...) is a structure of type STARSHIP.
NAME "Enterprise"
SPEED 1
CONDITION YELLOW
SHIELDS UP
EQUALITY OF STRUCTURES
The EQUAL function does not treat two distinctstructures as equal even if they have the same components
However, the EQUALP function will treat two structures as equal if they are of the same type and all their components are equal.
INHERITANCEFROM OTHER STRUCTURES
The fields of a STARSHIP structure include all the componentsof SHIP
(defstruct ship
(name nil)
(captain nil)
(crew-size nil))
(defstruct (starship (:include ship))
(weapons nil)
(shields nil))