# 3.5 Vectors

> A vector is a list that grows and shrinks while the program runs; all its elements have the same type.

Web page: https://pseudolearn.app/en/spec/tipos/vectores

> **In one sentence**
>
> A vector is a list that grows and shrinks while the program runs; all its elements have the same type.

## 3.5.1 How to write it

```pseudolearn
Define «name» As vector<«type»> <- vector();
«name».append(«value»);
«name».insert(«position», «value»);
«name».remove(«position»);
«name»[«position»]
```

## 3.5.2 How it works

Unlike an array, a **vector** has no fixed size. It starts empty and grows with `append` (at the end) or `insert` (at a position); it shrinks with `remove`. Positions count from zero and `length` says how many elements it has.

### Program: The shopping list

```pseudolearn
Algorithm Compra
  Define lista As Vector<String> <- vector();
  lista.append("pan");
  lista.append("leche");
  lista.insert(0, "fruta");
  Write lista, " ", lista.length();
  lista.remove(1);
  lista.sort();
  Write lista, " ", lista.contains("pan");
EndAlgorithm
```

**Output**

```text
["fruta", "pan", "leche"] 3
["fruta", "leche"] false
```

*The program finishes normally.*

**Figure 3.5-1: A vector that changes size**

A dashed box representing the vector lista, with positions numbered 0, 1 and 2. Stepping forward, pan and leche appear; then fruta at the start, shifting the others; finally pan disappears and leche moves to position 1.

A vector grows and shrinks. Inserting shifts what was already there to the right; removing closes the gap.

1. Step 1: The vector starts empty.
2. Step 2: `append` puts "pan" at the end and then "leche".
3. Step 3: `insert(0, …)` puts "fruta" at the start and shifts the rest.
4. Step 4: `remove(1)` takes out position 1 and the rest moves left.

## 3.5.3 A shared reference

A vector is a **reference**: two variables can point to the same vector. If it is changed through one of them, the other sees the change, because there are not two vectors but one.

### Program: Two names, a single vector

```pseudolearn
Algorithm Compartido
  Define a As Vector<Integer> <- vector();
  Define b As Vector<Integer> <- a;
  b.append(5);
  Write a.length(), " ", a;
EndAlgorithm
```

**Output**

```text
1 [5]
```

*The program finishes normally.*

To get an independent copy, use `copy`.

## 3.5.4 Methods

| Method | What it does |
| --- | --- |
| `append(x)` | Adds at the end |
| `insert(i, x)` | Adds at position `i` (from 0 to the length) |
| `remove(i)` | Takes out position `i` |
| `length()` | How many elements there are |
| `sort()` | Sorts from smallest to largest; accepts a comparator |
| `reverse()` | Turns the order around |
| `contains(x)` | `True` if `x` is there |
| `indexOf(x)` | `Some(position)` or `None` |

> **Limit**
>
> - Positions: from 0 to `length() - 1`. `insert` also accepts `length()` (at the end).
> - The natural order of `sort` works for `Integer`, `Real`, `Character`, `String` and `Boolean` (`False` before `True`); it is stable.
> - The maximum size is set by the engine's memory budget; exceeding it produces `collectionLimitExceeded`.
> - `Write` shows the elements between brackets separated by comma and space, with strings in quotes.

> **Common mistakes**
>
> Reading or removing a position that does not exist stops the program:
>
> ### Program: Removing from an empty vector
>
> ```pseudolearn
> Algorithm Vacio
>   Define v As Vector<Integer> <- vector();
>   v.remove(0);
> EndAlgorithm
> ```
>
> **Diagnostics**
> - `arrayIndexOutOfRange` (error, 3:3): Index 0 is out of range for an array of size 0
>
> *The program finishes with an error.*
>
> And a vector whose elements cannot be written does not accept `Write`:
>
> ### Program: A vector of records
>
> ```pseudolearn
> Record Caja
>   Define valor As Integer;
> EndRecord
> Algorithm NoImprimible
>   Define cajas As Vector<Caja> <- vector();
>   Write cajas;
> EndAlgorithm
> ```
>
> **Diagnostics**
> - `collectionCannotBeWritten` (error, 6:3): Collection elements have no output representation
>
> *The program finishes with an error.*

> **Under the hood**
>
> A vector lives on the heap: the variable holds a reference. Its capacity starts at zero, becomes one and then doubles each time it fills up, so appending at the end is cheap almost always. Every structural change increments an internal version that makes it possible to detect whether someone modifies it while it is being iterated.
>
> **Intermediate representation**
>
> ```text
> module Compartido en
> class "$vector<integer>" { "$leaf:value": i64 }
> func suspendible @main() -> unit {
> b0() mass 4:
>   stmt.enter @2:3-2:42
>   %0 = collection.new obj<"$vector<integer>"> @2:34-2:42
>   stmt.exit @2:3-2:42
>   stmt.enter @3:3-3:35
>   %1 = value.require %0 @3:3-3:35
>   stmt.exit @3:3-3:35
>   stmt.enter @4:3-4:14
>   %2 = const.i64 5 @4:12-4:13
>   %3 = collection.length %1 @4:3-4:14
>   collection.insert %1, %3, %2 @4:3-4:14
>   stmt.exit @4:3-4:14
>   stmt.enter @5:3-5:27
>   %4 = collection.length %0 @5:9-5:19
>   %5 = const.char ' ' @5:21-5:24
>   %6 = const.str "[" @5:26-5:27
>   %7 = const.i64 0
>   jump b1(%7, %6)
> b1(%8: i64, %9: str) mass 0:
>   %10 = collection.length %0 @5:26-5:27
>   %11 = int.cmp lt, %8, %10
>   branch %11, b2(), b3()
> b2() mass 0:
>   %12 = int.cmp eq, %8, %7
>   branch %12, b4(), b5()
> b3() mass 0:
>   %13 = const.str "]" @5:26-5:27
>   %14 = text.concat %9, %13 @5:26-5:27
>   out.write %4, %5, %14, newline @5:3-5:27
>   stmt.exit @5:3-5:27
>   return @6:1-6:13
> b4() mass 0:
>   jump b6(%9)
> b5() mass 0:
>   %15 = const.str ", " @5:26-5:27
>   %16 = text.concat %9, %15 @5:26-5:27
>   jump b6(%16)
> b6(%17: str) mass 0:
>   %18 = collection.load i64, %0, %8, 0 @5:26-5:27
>   %19 = text.format %18 @5:26-5:27
>   %20 = text.concat %17, %19 @5:26-5:27
>   %21 = const.i64 1
>   %22 = int.add %8, %21 @5:26-5:27
>   jump b7()
> b7() mass 0:
>   task.yield_check @1:1-1:21
>   jump b1(%22, %20) @1:1-1:21
> }
> ```

**In short**
- A vector grows and shrinks; all its elements have the same type.
- Positions from zero; going outside is a failure.
- It is a reference: assigning it shares the same vector.
- `copy` creates an independent one.

**See also**
- [3.4 Arrays](https://pseudolearn.app/en/spec/tipos/arreglos.md)
- [6.6 Walking collections with For Each](https://pseudolearn.app/en/spec/control/para-cada.md)
- [9.6 Copies, references and identity](https://pseudolearn.app/en/spec/objetos/copia.md)
