next up previous
Contents Next: Strings Up: ArraysVectors, and Previous: ArraysVectors, and

Arrays and Vectors

An array is a special type of data object in Lisp. Arrays are created using the make-array function. To make an array it is necessary to specify the size and dimensions. The simplest case is an array of one dimension, also called a vector.

Make-array returns an array. Most often one wants to bind this array to a symbol. Here's an example:

> (setf my-vector (make-array '(3)))
#(NIL NIL NIL)
In this case, the argument to make-array specified that the array should have one dimension of three elements. The array that was returned has three elements, all of them initially set to nil. (The actual printed representation of the array may vary between different Lisp implementations.)

These elements can be accessed and changed using aref. These examples illustrate:

> (aref my-vector 2)
NIL

> (setf (aref my-vector 0) t)
T

> my-vector
#(T NIL NIL)
Indexing of arrays starts with 0. (Just like indexing of lists using nth.) Here's an example of a two-dimensional array and some assignments.

> (setf my-array (make-array '(2 3)))
#2A((NIL NIL NIL) (NIL NIL NIL))

> (aref my-array 0 1)
NIL

> (setf (aref my-array 0 1) 'hi)
HI

> (setf (aref my-array 1 0) 'bye)
BYE

> my-array
#2A((NIL HI NIL) (BYE NIL NIL))
From this example you should be able to work out the indexing scheme.

Make array has a number of additional features we will not cover here. However, one that is particularly useful is the :initial-contents keyword. Here is an example to illustrate the use of :initial-contents.

> (make-array '(2 3 4) :initial-contents
             '(((a b c d) (e f g h) (i j k l))
               ((m n o p) (q r s t) (u v w x))))
#3A(((A B C D) (E F G H) (I J K L)) ((M N O P) (Q R S T) 
     (U V W X)))
Initial contents are specified with a list of elements having the required sublist structure to match the array.

The use of :initial-contents is entirely optional with make-array, as is the use of other keywords not introduced here.

Programmers like to use arrays because they give uniformly fast access to all their elements. In general, however, arrays are less flexible for representing structure than lists. Consider the structure represented in this list:

(a (b c) (d e f (g h)))
No array can concisely reproduce this structure, since it must have a uniform number of elements for each of its dimensions.



© Colin Allen & Maneesh Dhagat
March 2007