On this page:
Sequences are variable-length collections of elements:
{zcode:slice} sequence<Fruit> FruitPlatter; {zcode} |
A sequence can be empty — that is, it can contain no elements, or it can hold any number of elements up to the memory limits of your platform.
Sequences can contain elements that are themselves sequences. This arrangement allows you to create lists of lists:
{zcode:slice} sequence<FruitPlatter> FruitBanquet; {zcode} |
Sequences are used to model a variety of collections, such as vectors, lists, queues, sets, bags, or trees. (It is up to the application to decide whether or not order is important; by discarding order, a sequence serves as a set or bag.)
One particular use of sequences has become idiomatic, namely, the use of a sequence to indicate an optional value. For example, we might have a Part
structure that records the details of the parts that go into a car. The structure could record things such as the name of the part, a description, weight, price, and other details. Spare parts commonly have a serial number, which we can model as a long
value. However, some parts, such as simple screws, often do not have a serial number, so what are we supposed to put into the serial number field of a screw? There are a number of options for dealing with this situation:
long
to string
.string
just so we get a sentinel value.{zcode:slice} struct Part { string name; string description; // ... bool serialIsValid; // true if part has serial number long serialNumber; }; {zcode} |
{zcode:slice} sequence<long> SerialOpt; struct Part { string name; string description; // ... SerialOpt serialNumber; // optional: zero or one element }; {zcode} |
Opt
suffix is used to indicate that the sequence is used to model an optional value. If the sequence is empty, the value is obviously not there; if it contains a single element, that element is the value. The obvious drawback of this scheme is that someone could put more than one element into the sequence. This could be rectified by adding a special-purpose Slice construct for optional values. However, optional values are not used frequently enough to justify the complexity of adding a dedicated language feature. (As we will see in Classes, you can also use class hierarchies to model optional fields.)