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];
EndAlgorithmOutput
1 2 7
The program finishes normally.
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);
EndAlgorithmDiagnostics
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 animmutable.- An
immutableis read but not modified. - Whatever the original changes afterwards does not affect the snapshot.
- Immutables can move from one task to another.