Next: , Previous: , Up: Object Representation   [Contents][Index]


5.10.2 Structure Representation

One of the best ways of building complex data structures is to define appropriate structure types using defstruct. In Python, access of structure slots is always at least as fast as list or vector access, and is usually faster. In comparison to a list representation of a tuple, structures also have a space advantage.

Even if structures weren’t more efficient than other representations, structure use would still be attractive because programs that use structures in appropriate ways are much more maintainable and robust than programs written using only lists. For example:

(rplaca (caddr (cadddr x)) (caddr y))

could have been written using structures in this way:

(setf (beverage-flavor (astronaut-beverage x)) (beverage-flavor y))

The second version is more maintainable because it is easier to understand what it is doing. It is more robust because structures accesses are type checked. An astronaut will never be confused with a beverage, and the result of beverage-flavor is always a flavor. See sections structure-types and freeze-type for more information about structure types. See type-inference for a number of examples that make clear the advantages of structure typing.

Note that the structure definition should be compiled before any uses of its accessors or type predicate so that these function calls can be efficiently open-coded.


Next: Arrays, Previous: Think Before You Use a List, Up: Object Representation   [Contents][Index]