Skip to content

SpecificationIII · Types and values

3.13

immutable and snapshot

snapshot takes a complete picture of a value and returns it as immutable: everything can be read, but nobody can change it.

Markdown version

3.13.1 How it works

Vectors, dictionaries and arrays are shared: if someone modifies them, everyone sees it. Sometimes the opposite is needed, a value that cannot change. snapshot(x) copies x whole, with everything it contains, and returns an immutable of that type.

ProgramA picture that does not change

Algorithm Congelar
  Define notas As Vector<Integer> <- vector();
  notas.append(7);
  Define foto As Immutable<Vector<Integer>> <- snapshot(notas);
  notas.append(9);
  Write foto.length(), " ", notas.length(), " ", foto[0];
EndAlgorithm

Output

1 2 7

The program finishes normally.

Figure 3.13-1.The snapshot copies the whole content. Whatever happens to the original afterwards does not affect the picture.

The vector notas held a 7 when the snapshot was taken; a 9 was added afterwards. The picture, with a padlock, keeps only the 7: it can be read but not written.

An immutable allows every read, but no write and no modifying method:

ProgramTrying to change the picture

Algorithm EscribirFoto
  Define notas As Vector<Integer> <- vector();
  Define foto As Immutable<Vector<Integer>> <- snapshot(notas);
  foto.append(9);
EndAlgorithm

Diagnostics

  • immutableValueWrite · error · 4:3 · An immutable value cannot be modified

The program finishes with an error.

3.13.2 Why it exists

Concurrent tasks cannot share vectors or dictionaries, because two tasks could change them at the same time. An immutable can cross between tasks: since nobody modifies it, sharing it is safe.

In short

  • snapshot(x) copies everything and returns an immutable.
  • An immutable is read but not modified.
  • Whatever the original changes afterwards does not affect the snapshot.
  • Immutables can move from one task to another.