A Guide to the S-Lang Language: Associative Arrays

Next Previous Contents

## 12. Associative Arrays

An associative array differs from an ordinary array in the sense that its size is not fixed and that is indexed by a string, called the key. For example, consider:

> `

>            variable A = Assoc_Type [Integer_Type];
>            A["alpha"] = 1;
>            A["beta"] = 2;
>            A["gamma"] = 3;

> `

Here, `A` represents an associative array of integers (`Integer_Type`) and three keys have been added to the array.

As the example suggests, an associative array may be created using one of the following forms:

> `Assoc_Type [type] Assoc_Type [type, default-value] Assoc_Type []`

The last form returns an associative array of `Any_Type` objects allowing any type of object to may be stored in the array.

The form involving a default-value is useful for associating a default value for non-existent array members. This feature is explained in more detail below.

There are several functions that are specially designed to work with associative arrays. These include:

- `assoc_get_keys`, which returns an ordinary array of strings containing the keys in the array.
- `assoc_get_values`, which returns an ordinary array of the values of the associative array.
- `assoc_key_exists`, which can be used to determine whether or not a key exists in the array.
- `assoc_delete_key`, which may be used to remove a key (and its value) from the array.

To illustrate the use of an associative array, consider the problem of counting the number of repeated occurrences of words in a list. Let the word list be represented as an array of strings given by `word_list`. The number of occurrences of each word may be stored in an associative array as follows:

> `

>          variable a, word;
>          a = Assoc_Type [Integer_Type];
>          foreach (word_list)
>            {
>               word = ();
>               if (0 == assoc_key_exists (a, word))
>                 a[word] = 0;
>               a[word]++;  % same as a[word] = a[word] + 1;
>            }

> `

Note that `assoc_key_exists` was necessary to determine whether or not a word was already added to the array in order to properly initialize it. However, by creating the associative array with a default value of `0`, the above code may be simplified to

> `

>          variable a, word;
>          a = Assoc_Type [Integer_Type, 0];
>          foreach (word_list)
>            {
>               word = ();
>               a[word]++;
>            }

> `

Next Previous Contents