Arrays

An array is a contiguous block of memory that is divided into elements that are indexed by an integer.

The indices of the array are specified by a range of two integers m..n where $m \leq n$, and the size of the array is $m - n + 1$. The default value of the elements of the array is 0:

[> A1 := Array( 7..15 ):

In general, simply refrain from printing out arrays, as this is an $\textrm{O}(n)$ operation, and thus defeats the purpose of using them.

You can assign to any index in the range, so in this case, from $7$ to $15$, and trying to access or assign to an index outside this range results in an error:

[> A1[8] := x;

$A1_{8} := x$

[> A1[15];

$0$

[> A1[6];
Error, Array index out of range
[> A1[16];
Error, Array index out of range

If you require an empty array (one with no valid indices), you can use, for example:

[> A2 := Array( 1..0 );

$A2 := []$

Initializing arrays

Once you have specified the range of indices, you can specify the initial values in one of the following three ways:

  1. A list of expresssions which can have more or less elements than the array will have. The first entry of the list is assigned to the first index of the array, then next entry of the list to the next index, and so on until either we run out of elements in the list to assign to the entries of the array, or we have given each element in the array a value. If there are not enough elements in the list, all subsequent elements are assigned 0.
  2. A function mapping the index onto a value. Each entry of the array will be given a value using this technique.
  3. A set of equations of the form index = value where the index is an integer between the lower and upper bounds of the array, and the value is what will be assigned to that index. If an entry is not initialized, it is initialized to zero.

For example:

[> # Create the array [17, 18, 19, 20, 0, 0, 0, 0, 0]
[> # indexed from 7 to 15
[> A3 := Array( 7..15, [17, 18, 19, 20] ):

[> # Create the array [25, 16, 9, 4, 1, 0, 1, 4]
[> # indexed from -5 to 2
[> A4 := Array( -5..2, n -> n^2 ):

[> # Create the array [0, x + 1, 0, 0, x^2, 0, x - 1, 0]
[> # indexed from -12 to -5
[> A3 := Array( -12..-5, {-8 = x^2, -11 = x + 1, -6 = x - 1} ):

In each of these, you can access or assign to the entries in a constant run time. This is much more efficient than a list, where changing an entry in a list requires the generation of a completely new list, so the run time is $\textrm{O}(n)$.

There are other features of such arrays that are not documented here, which you can read about in the help pages.