# 6.6 Walking collections with For Each

> `For Each` visits the elements of a vector, an array or a dictionary one by one, without indices.

Web page: https://pseudolearn.app/en/spec/control/para-cada

> **In one sentence**
>
> `For Each` visits the elements of a vector, an array or a dictionary one by one, without indices.

## 6.6.1 How to write it

```pseudolearn
For Each «elemento» In «colección» Do
  «instrucciones»
EndFor
For Each «clave», «valor» In «diccionario» Do
  «instrucciones»
EndFor
```

> **Parts**
>
> - `For Each` opens the traversal.
> - «element» is a new name that, on every round, holds the visited element. It cannot be assigned.
> - `In` separates the names from the collection.
> - «collection» is a `Vector`, a one-dimensional array or, with two names, a `Dictionary`.
> - `EndFor` closes the traversal.

## 6.6.2 How it works

The collection is computed once. Then every element is visited in order: from position 0 onwards for vectors and arrays, and in insertion order for dictionaries. An empty collection does not run the body.

### Program: Walking a vector

```pseudolearn
Algorithm Mochila
  Define lista As Vector<String> <- vector();
  lista.append("pan");
  lista.append("leche");
  lista.append("huevos");
  For Each producto In lista Do
    Write "- ", producto;
  EndFor
EndAlgorithm
```

**Output**

```text
- pan
- leche
- huevos
```

*The program finishes normally.*

**Figure 6.6-1: Walking a vector**

A vector with pan, leche and huevos at positions 0, 1 and 2. A frame moves through each cell and producto takes the value of the framed cell.

The traversal moves through the cells in order. On every round, `producto` holds a copy of the visited element.

1. Step 1: First round: `producto` is `"pan"`.
2. Step 2: Second round: `producto` is `"leche"`.
3. Step 3: Third round: `producto` is `"huevos"`. There are no more and the traversal ends.

With a dictionary two names are needed, the key and the value:

### Program: Walking a dictionary

```pseudolearn
Algorithm Edades
  Define edades As Dictionary<String, Integer> <- dictionary();
  edades["Ana"] <- 12;
  edades["Leo"] <- 11;
  For Each nombre, edad In edades Do
    Write nombre, ": ", edad;
  EndFor
EndAlgorithm
```

**Output**

```text
Ana: 12
Leo: 11
```

*The program finishes normally.*

> **Limit**
>
> During the traversal the collection cannot change its **structure**: adding or removing elements stops the program with `collectionModifiedDuringIteration`, even when done through another name. Replacing the value of an existing element is allowed.

> **Common mistakes**
>
> ### Program: Adding while walking
>
> ```pseudolearn
> Algorithm Modificar
>   Define lista As Vector<Integer> <- vector();
>   lista.append(1);
>   lista.append(2);
>   For Each n In lista Do
>     lista.append(n);
>   EndFor
> EndAlgorithm
> ```
>
> **Diagnostics**
> - `collectionModifiedDuringIteration` (error, 5:3): The collection was structurally modified during iteration
>
> *The program finishes with an error.*

> **Under the hood**
>
> The traversal keeps the version of the collection when it starts and compares it before every step. If it does not match, the trap is raised.
>
> **Intermediate representation**
>
> ```text
> module Mochila en
> class "$vector<string>" { "$leaf:value": str }
> func suspendible @main() -> unit {
> b0() mass 5:
>   stmt.enter @2:3-2:45
>   %0 = collection.new obj<"$vector<string>"> @2:37-2:45
>   stmt.exit @2:3-2:45
>   stmt.enter @3:3-3:22
>   %1 = const.str "pan" @3:16-3:21
>   %2 = collection.length %0 @3:3-3:22
>   collection.insert %0, %2, %1 @3:3-3:22
>   stmt.exit @3:3-3:22
>   stmt.enter @4:3-4:24
>   %3 = const.str "leche" @4:16-4:23
>   %4 = collection.length %0 @4:3-4:24
>   collection.insert %0, %4, %3 @4:3-4:24
>   stmt.exit @4:3-4:24
>   stmt.enter @5:3-5:25
>   %5 = const.str "huevos" @5:16-5:24
>   %6 = collection.length %0 @5:3-5:25
>   collection.insert %0, %6, %5 @5:3-5:25
>   stmt.exit @5:3-5:25
>   stmt.enter @6:3-8:9
>   %7 = collection.version %0 @6:3-8:9
>   %8 = collection.length %0 @6:3-8:9
>   %9 = const.i64 0
>   jump b1(%9)
> b1(%10: i64) mass 0:
>   collection.check %0, %7 @6:3-8:9
>   %11 = int.cmp lt, %10, %8 @6:3-8:9
>   decide.bool %11 @6:3-8:9
>   branch %11, b2(), b3()
> b2() mass 1:
>   %12 = collection.load str, %0, %10, 0 @6:3-8:9
>   stmt.enter @7:5-7:25
>   %13 = const.str "- " @7:11-7:15
>   out.write %13, %12, newline @7:5-7:25
>   stmt.exit @7:5-7:25
>   %14 = const.i64 1
>   %15 = int.add %10, %14 @6:3-8:9
>   jump b4()
> b3() mass 0:
>   stmt.exit @6:3-8:9
>   return @9:1-9:13
> b4() mass 0:
>   task.yield_check @1:1-1:18
>   jump b1(%15) @1:1-1:18
> }
> ```

**In short**
- `For Each` visits every element in order, without indices.
- With dictionaries two names are written: key and value.
- The element name cannot be assigned.
- Changing the structure of the collection during the traversal is a failure.

**See also**
- [6.5 The counted loop For](https://pseudolearn.app/en/spec/control/para.md)
- [3.5 Vectors](https://pseudolearn.app/en/spec/tipos/vectores.md)
- [3.6 Dictionaries](https://pseudolearn.app/en/spec/tipos/diccionarios.md)
