20.1. Lists and entries

| Chapter 20: Lists |

| 20.1. Lists and entries

Many sections in this book begin by introducing a new kind of value. Reading through in order, the possibilities mount up: numbers, times, texts (and indexed texts), and so on. (See the Kinds page of the Index for a convenient list of the options.) This section is a little different: rather than showing a single new kind of value, it shows how to make a new kind out of any existing one.

If K is any kind of value, then "list of K" is also a kind of value. For instance, we could write:

> let L be a list of numbers;

and this would create a new "let" variable, called L, whose kind of value is "list of numbers". On the other hand, we are not allowed to write:

> let L be a list;

because "list" by itself is not a kind of value. (Inform always needs to know what kinds the values entered in a list are going to have.)

Lists are like flexible-length table columns, but that probably makes them sound more mysterious than they really are. A list is simply a sequence of values, called its "entries", numbered from 1 upwards. The number of entries is called its "length". If we try

> let L be a list of numbers;
> say "L has [the number of entries in L] entries.";

then we find

> L has 0 entries.

This is because all lists start out empty when created: that is, they initially have 0 entries. Inform has two built-in adjectives "empty" and "non-empty" which can apply to lists, and they mean just what they ought to mean: a list is empty if its length is 0, and otherwise non-empty.

We can add entries very easily:

> add 2 to L; add 3 to L; add 5 to L;

We can now, for instance, try saying the list:

> say "L is now [L].";

with the result

> L is now 2, 3 and 5.

Note that only numbers can be added to L: if we try

> add "clock" to L;

Inform will produce a problem message, because L has kind "list of numbers", whereas "clock" is text. In this way, Inform ensures that a list always contains values of the same kind throughout. So it's not possible to construct a list whose entries are:

> 2, "fish", 4 and the Entire Game

Such a list would be very hazardous to deal with, in any case. If what we need is a combination of different kinds of values, tables are a better option.

Finally, note that since "list of numbers" is a kind of value in its own right, so is "list of lists of numbers", and so on - though such lists are trickier to deal with, they are sometimes handy.

Previous | Contents | Next