Using Association Lists to Bundle Data

AutoCAD Visual LISP

 
Using Association Lists to Bundle Data
 
 
 

The previous example works, but you can do better. In the next exercise, you will build an association list, or assoc list (after the LISP function that deals with association lists). In an association list, the values you are interested in are associated with key values. Here is a sample association list:

((10 4.46207 4.62318 0.0) (11 7.66688 4.62318 0.0) (40 . 1.018248))

In the sample association list, the key values are the numbers 10, 11, and 40. These key values serve as a unique index within the list. This is the mechanism AutoCAD uses to return entity data to AutoLISP if you access an entity from within your program. A key value of 10 indicates a start point, a key value of 11 is typically an endpoint.

What are the advantages of an association list? For one thing, unlike the regular list, the order of the values returned does not matter. Look at the first list again:

((4.46207 4.62318 0.0) (7.66688 4.62318 0.0) 0.509124)

Look at the return values; it is not apparent which sublist is the start point and which is the endpoint. Furthermore, if you modify the function in the future, any other function that relies on data returned in a specific order may be adversely affected.

Using an association list, the order of the values does not matter. If the order of an association list changes, you can still tell which value defines what. For example, an 11 value is still an endpoint, regardless of where it occurs within the overall list:

((11 7.66688 4.62318 0.0)      ; order of list
 (40 . 1.018248)               ; has been
 (10 4.46207 4.62318 0.0))     ; modified