next up previous contents
Next: Matrices Up: Lists and Arrays Previous: Lists

   
Arrays

The array data type is identical to the list data type in Darwin as both implement ordered multisets. The difference between the two is solely conceptual: (in computer science terms) lists are typically thought of as finite chains of data while an array is thought of as indexed collection of data. Let us make this a bit more clear with an example.

We could define an empty array with four elements and assign to each element independently. To define an empty array, we use the CreateArray function.

> animals := CreateArray(1..4);
animals := [0, 0, 0, 0]
Each of the four elements of animals is initialized to the value 0. To assign to each element, we index the variable name animals.
> animals[1] := 'chimpanzee';
animals[1] := chimpanzee
> animals[2] := 'gorilla';
animals[2] := gorilla
> animals[3] := 'monkey';
animals[3] := monkey
> animals[4] := 'orangutan';
animals[4] := orangutan

To examine the contents of the list we again index the variable name with the location or the range of locations we are interested in.

> animals[1];
chimpanzee
> animals[2..4];              # examine only the last 3 elements of the array
[gorilla, monkey, orangutan]


  
Figure: A one dimensional array.
\begin{figure}\centerline{\psfig{file=Diagrams/array.ps,width=5in}}
\end{figure}

There is absolutely no semantic difference between the two types. The synonyms are offered because it is sometimes more appropriate to think of your data as a list than an array and vice versa.

We can define an array of two dimensions by specifying a second range as an argument to the CreateArray command. To access the elements, we specify the index in both dimensions separated by a comma.1.3

> square := CreateArray(1..5, 1..7);
> square[1, 3] := 5;          # assign 5 to the element in 
                              #   row 1, column 3
square[1,3] := 5
> square[5, 7] := 10;         # assign 10 to the element in 
                              #   row 5, column 7
square[5,7] := 10


next up previous contents
Next: Matrices Up: Lists and Arrays Previous: Lists
Gaston Gonnet
1998-09-15