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?
What happens here is that when the list of
k->k+1maps is returned, it takes the current value ofi(local variable defined inget_maps) which is 3 after theforloop has been completed.You can avoid this by placing the function creation within a function (in the example called
construct_map: Then theiadded is always the local variablei, which for each iteration of the function will be a different variable, assigned to a different value.Try the following:
Then it works as desired:
However all three functions with
Printask->k+i, wirth the value ofihidden. 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.