Common Lisp the Language, 2nd Edition


next up previous contents index
Next: Other Aspects of Up: Structures of Explicitly Previous: Unnamed Structures

19.7.2. Named Structures

A ``named'' structure has the property that, given an instance of the structure, the structure name (that names the type) can be reliably recovered. For structures defined with no :type option, the structure name actually becomes part of the Common Lisp data-type system. The function type-of, when applied to such a structure, will return the structure name as the type of the object; the predicate typep will recognize the structure name as a valid type specifier.

For structures defined with a :type option, type-of will return a type specifier such as list or (vector t), depending on the type specified to the :type option. The structure name does not become a valid type specifier. However, if the :named option is also specified, then the first component of the structure (as created by a defstruct constructor function) will always contain the structure name. This allows the structure name to be recovered from an instance of the structure and allows a reasonable predicate for the conceptual type to be defined: the automatically defined name-p predicate for the structure operates by first checking that its argument is of the proper type (list, (vector t), or whatever) and then checking whether the first component contains the appropriate type name.

Consider the binop example shown above, modified only to include the :named option:

(defstruct (binop (:type list) :named) 
  (operator '? :type symbol) 
  operand-1 
  operand-2)

As before, this will define a constructor function make-binop and three selector functions binop-operator, binop-operand-1, and binop-operand-2. It will also define a predicate binop-p.

The effect of make-binop is now to construct a list of length 4:

(make-binop :operator '+ :operand-1 'x :operand-2 5) 
   => (binop + x 5) 

(make-binop :operand-2 4 :operator '*) 
   => (binop * nil 4)

The structure has the same layout as before except that the structure name binop is included as the first list element. The selector functions binop-operator, binop-operand-1, and binop-operand-2 are essentially equivalent to cadr, caddr, and cadddr, respectively. The predicate binop-p is more or less equivalent to the following definition.

(defun binop-p (x) 
  (and (consp x) (eq (car x) 'binop)))

The name binop is still not a valid type specifier recognizable to typep, but at least there is a way of distinguishing binop structures from other similarly defined structures.



next up previous contents index
Next: Other Aspects of Up: Structures of Explicitly Previous: Unnamed Structures


AI.Repository@cs.cmu.edu