11.5.4 Tables: Dynamic associations

In Section 11.5.3, we saw how the color-action method associated traffic-light colors with actions by using select. These associations are static. They are determined at compile time, and you cannot change them without recompiling the color-action method. Sometimes, it is useful to associate one object with another dynamically, while the program is running. Collections are good data structures for this purpose. How could we rewrite color-action so that it uses a collection to associate colors with actions?

define variable *color-action-table* = make(<table>, size: 3);
*color-action-table*[#"red"]    := #"stop";
*color-action-table*[#"yellow"] := #"slow";
*color-action-table*[#"green"]  := #"go";
define method color-action (color :: <symbol>) => (action :: <symbol>)
  *color-action-table*[color];
end method color-action;

The tables provided by Dylan use == to compare keys.

During the execution of the program, we could add new associations to *color-action-table*, or could change or remove existing associations. Tables grow as necessary to accommodate new associations that are added.