Chapter 20: Lists
20.10. Lengthening or shortening a list

We can explicitly change the length of a list like so:

change L to have 21 entries;

If L previously had more than 21 entries, they are thrown away (and lost forever); if L previously had fewer, then new entries are created, using the default value for whatever kind of value L holds. So extending a list of numbers will pad it out with 0s, but extending a list of texts will pad it out with the empty text "", and so on.

We can also write the slightly different phrases:

truncate L to 8 entries;
truncate L to the last 4 entries;
extend L to 80 entries;

The first means "shorten L to length 8 if it is currently longer than that", and would (for instance) leave a list of length 3 unchanged; the second is similar, but trims excess entries from the front rather than the back; the third means "lengthen L to length 80 if it is currently shorter than that". Note that

truncate L to 0 entries;

shortens L right back down to the empty list, the shortest it can be.

For example,

To check sorting (N - a number):
    let L be a list of numbers;
    extend L to N entries;
    repeat with X running from 1 to N:
        change entry X of L to X;
    say "L unrandomised is [L].";
    sort L in random order;
    say "L randomised is [L].";
    sort L;
    say "L in ascending order is [L]."

builds a list of N numbers (initially all 0), fills it with the numbers 1, 2, 3, ..., N, then randomly reorders them, then sorts them back again, recovering the original order. The text produced by "check sorting 10" depends partly on chance but might for instance be:

L unrandomised is 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10.
L randomised is 6, 2, 9, 3, 10, 1, 7, 4, 8 and 5.
L in ascending order is 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10.

As with indexed text in the previous chapter, a project which needs really long lists should use the Glulx virtual machine - "check sorting 10000", for instance, would break the default memory environment on the Z-machine, which is very tight, but works fine (if not very rapidly) on Glulx.


412
* Example  Leopard-skin
A maze that the player can escape if he performs an exact sequence of actions.

RB
413
** Example  The Facts Were These
Creating a variant GIVE action that lets the player give multiple objects simultaneously with commands like GIVE ALL TO ATTENDANT or GIVE THREE DOLLARS TO ATTENDANT or GIVE PIE AND HAT TO ATTENDANT. The attendant accepts the gifts only if their total combined value matches some minimum amount.

RB


PreviousContentsNext