Replace variable by value in gap

47 Views Asked by At

I want to generate a list of maps in a function and return this list. For example the list of maps $$ [k\mapsto k+1,\ k\mapsto k+2,\ k\mapsto k+3] $$ I thought I could do this by the following code:

get_maps := function()
   local maps,i;
   maps := [];
   for i in [1..3] do
      Add(maps,k->k+i);
   od;
   return maps;
end;

But the value of i changes inside the function. So in fact I get three identical mappings $k\mapsto k+3$.

How can I access the value of i inside the function instead of the variable i?

1

There are 1 best solutions below

3
On BEST ANSWER

What happens here is that when the list of k->k+1 maps is returned, it takes the current value of i (local variable defined in get_maps) which is 3 after the for loop has been completed.

You can avoid this by placing the function creation within a function (in the example called construct_map: Then the i added is always the local variable i, which for each iteration of the function will be a different variable, assigned to a different value.

Try the following:

get_maps := function()
   local maps, i, construct_map;
   maps := [];
   construct_map := i -> (k -> k+i);
   for i in [1..3] do
      Add( maps, construct_map(i) );
   od;
   return maps;
end;

Then it works as desired:

gap> f:=get_maps();
[ function( k ) ... end, function( k ) ... end, function( k ) ... end ]
gap> List(f, t -> t(1));
[ 2, 3, 4 ]

However all three functions with Print as k->k+i, wirth the value of i hidden. If you really want the functions to be (e.g.) k->k+3, you would have to produce a string with the function definition (including the concrete number) and evaluate it.