Copy( obj )
Copy
returns a copy new of the object obj. You may apply Copy
to
objects of any type, but for objects that are not lists or records Copy
simply returns the object itself.
For lists and records the result is a new list or record that is not identical to any other list or record (see Identical Lists and Identical Records). This means that you may modify this copy new by assignments (see List Assignment and Record Assignment) or by adding elements to it (see Add and Append), without modifying the original object obj.
gap> list1 := [ 1, 2, 3 ];; gap> list2 := Copy( list1 ); [ 1, 2, 3 ] gap> list2[1] := 0;; list2; [ 0, 2, 3 ] gap> list1; [ 1, 2, 3 ]
That Copy
returns the object itself if it is not a list or a record is
consistent with this definition, since there is no way to change the
original object obj by modifying new, because in fact there is no way
to change the object new.
Copy
basically executes the following code for lists, and similar code
for records.
new := []; for i in [1..Length(obj)] do if IsBound(obj[i]) then new[i] := Copy( obj[i] ); fi; od;
Note that Copy
recursively copies all elements of the object obj. If
you only want to copy the top level use ShallowCopy
(see
ShallowCopy).
gap> list1 := [ [ 1, 2 ], [ 3, 4 ] ];; gap> list2 := Copy( list1 ); [ [ 1, 2 ], [ 3, 4 ] ] gap> list2[1][1] := 0;; list2; [ [ 0, 2 ], [ 3, 4 ] ] gap> list1; [ [ 1, 2 ], [ 3, 4 ] ]
The above code is not entirely correct. If the object obj contains a list or record twice this list or record is not copied twice, as would happen with the above definition, but only once. This means that the copy new and the object obj have exactly the same structure when view as a general graph.
gap> sub := [ 1, 2 ];; list1 := [ sub, sub ];; gap> list2 := Copy( list1 ); [ [ 1, 2 ], [ 1, 2 ] ] gap> list2[1][1] := 0;; list2; [ [ 0, 2 ], [ 0, 2 ] ] gap> list1; [ [ 1, 2 ], [ 1, 2 ] ]
GAP 3.4.4