3.3 Immutability

GAP has a mechanism that protects lists against changes like the ones that have bothered us in Section Identical Lists. The function Immutable takes as argument a list and returns an immutable copy of it, i.e., a list which looks exactly like the old one, but has two extra properties: (1) The new list is immutable, i.e., the list itself and its subobjects cannot be changed. (2) In constructing the copy, every part of the list that can be changed has been copied, so that changes to the old list will not affect the new one. In other words, the new list has no mutable subobjects in common with the old list.

gap> list := [ 1, 2, "three", [ 4 ] ];; copy := Immutable( list );;
gap> list[3][5] := 'w';; list; copy;
[ 1, 2, "threw", [ 4 ] ]
[ 1, 2, "three", [ 4 ] ]
gap> copy[3][5] := 'w';
Lists Assignment: <list> must be a mutable list
Entering break read-eval-print loop, you can 'quit;' to quit to outer \
loop,
or you can return and ignore the assignment to continue
brk> quit;
As a consequence of these rules, in the immutable copy of a list which contains an already immutable list as subobject, this immutable subobject need not be copied, because it is unchangeable. Immutable lists are useful in many complex GAP objects, for example as generator lists of groups. By making them immutable, GAP ensures that no generators can be added to the list, removed or exchanged. Such changes would of course lead to serious inconsistencies with other knowledge that may already have been calculated for the group.

A converse function to Immutable is ShallowCopy, which produces a new mutable list whose ith entry is the ith entry of the old list. The single entries are not copied, they are just placed in the new list. If the old list is immutable, and hence the list entries are immutable themselves, the result of ShallowCopy is mutable only on the top level.

It should be noted that also other objects than lists can appear in mutable or immutable form. Records (see Section Plain Records) provide another example.

[Top] [Previous] [Up] [Next] [Index]

GAP 4 manual
February 2000