[GAP Forum] list of list

Stephen Linton sl4 at st-andrews.ac.uk
Mon Feb 4 12:10:34 GMT 2013


Dear GAP Forum,


On 4 Feb 2013, at 11:38, Denise Torrão <denisetorrao at hotmail.com> wrote:

> 
> Hello, my name is Denise and I'm starting to work in GAP. I'm trying to compute a simple program, but I'm with some dificulty, because I implement a cycle for, and my values of the list change. The program is the following:
> algoritmo14:=function(p,D,c)
> local soma, soma2, aux, aux3,i,A,x;
> A:=[];A[1]:=[];x:=[];
> for j in [1..p-1] do	A[1][j]:=0;od;A[1][p]:=c;
> 
> for i in [1..p-1] do	x[i]:=0;od;x[p]:=c;
> i:=p-1;
> soma:=0;
> while (i>0) do	for aux in [i+1..p] do		soma:=soma+D[aux]*x[aux];	od;	if (soma >= D[i]) then		x[i]:=x[i]+1;				x[p]:=soma-D[i];
> 		for aux3 in [i+1..p-1] do			x[aux3]:=0;		od;Print("A1-> ",A,"\n");
> 		Add(A,x);Print("A2-> ",A,"\n");		i:=p-1;	else		i:=i-1;	fi;	soma:=0;od;
> 
> return A;end;	
> My problem is with the list A, that changes, and in the final all it's elements (except for the first one) are equal. Can someone help me? I guess is something very trivial, but as I said before, I'm taking my first steps with GAP, so I still have a lot of dificulties with this program.
> Very very thanks,
> Denise Torrão 		 	   		  

I think the problem is the statement "Add(A,x)". This DOES NOT make a copy of x.

A simple example is 

gap> l := [1];
[ 1 ]
gap> m := [];
[  ]
gap> Add(m,l);
gap> l[1] := 2;
2
gap> m;
[ [ 2 ] ]
gap> 

Here m[1] and l are THE SAME list and changes to that list can be seen through both routes. What you probably want is 

Add(A, ShallowCopy(x));

which does make a copy.

	Steve





More information about the Forum mailing list