11.2.2 Creation of vectors and access to elements

There are several ways to create collections. One way is to create a collection by using make. For example, here we create a vector that contains two elements:

? define variable *my-vector* = make(<vector>, size: 2);

We can change the first and second elements:

? *my-vector*[0] := 5;
5
? *my-vector*[1] := 3;
3
? *my-vector*;
#[5, 3]

If you want to create a sequence of a certain size, with every element having the same value, you can specify a fill keyword argument to make. The default value for the fill keyword parameter is #f. Thus, if you had read an element of *my-vector* before you wrote numbers into it, you would have received #f.

We can create and initialize a vector to different values all at once by using a built-in constructor. A constructor is a function that creates an instance; using it is a shorthand for calling make. Here, we use the vector constructor function to create a vector and to initialize it with data.

? define variable *my-vector* = vector(5, 3);
? *my-vector*;
#[5, 3]

As we saw in Section 11.2.1, certain collections have a literal syntax that enables you to specify a particular data structure as part of the program:

? define variable *my-vector* = #[5, 3];
? *my-vector*;
#[5, 3]

Figure 11.2 shows how you can picture the vector that we just created.

Figure 11.2 Diagram of the vector #[5, 3].

db14im17

You might think that *my-vector* is a direct instance of <vector>, but it is not: The <vector> class is abstract, but instantiable. When you use the vector function, or use make with <vector>, the result is a general instance of <simple-object-vector>. You specify the size of a <simple-object-vector> when you create one, and you cannot change that size later. If you need a vector that can change size, use the <stretchy-vector> class. See Section 16.1.1, page 246, for an example that uses stretchy vectors.