Advice: Constructing names of local variables and formal parameters

Names of global variables can be constructed by various string manipulations, e.g. concatenation. This is often very useful when you have a sequence of variables such as x1 , x2 , ...; in a loop, you can form the names by x||i where i is the index. However, this does not work with local variables or formal parameters in a procedure: the constructed names will refer to global variables. For example, the following procedure works, because the names involved are all global:

> test1:= proc()
local i;
for i from 1 to 3 do x||i:= g||i od;
end;

test1 := proc () local i; for i to 3 do x || i := g...

> test1():

> x1,x2,x3;

g1, g2, g3

However, the next one doesn't work: in the loop, v||i and p||i will refer to global variables rather than the local variables v1 , v2 , v3 or the formal parameters p1 , p2 , p3 .

> test2:= proc(p1,p2,p3)
local v1,v2,v3,i;
for i from 1 to 3 do v||i:= p||i od;
print(v1,v2,v3);
end;

test2 := proc (p1, p2, p3) local v1, v2, v3, i; for...
test2 := proc (p1, p2, p3) local v1, v2, v3, i; for...
test2 := proc (p1, p2, p3) local v1, v2, v3, i; for...
test2 := proc (p1, p2, p3) local v1, v2, v3, i; for...

> test2(u,v,w);

v1, v2, v3

> v1,v2,v3;

p1, p2, p3

The reason for this behaviour is connected to the way the Maple kernel processes procedure definitions. Internally, names are used for reference to global variables, but not local variables or formal parameters. For example:

> test3:= proc(x) local v; v:= x+g end:

> pointto(disassemble(addressof(eval(test3)))[6]);

loc[1] := args[1]+g

Thus in the internal version of the procedure definition, the local variable name v is replaced by LOC[1] , and the formal parameter name x is replaced by args[1] (more precisely, these are special constructions which Maple interprets as references to the first local variable and the first formal parameter). If a name is only produced when the procedure is executed, these replacements do not occur and the name is interpreted as a global variable. 

You can use args[i] to refer to the i 'th formal parameter, so constructing the formal parameter names should not be necessary. You can't use args[i] on the left side of an assignment statement, but you can use assign to assign values to the formal parameters (if these are declared as evaln parameters).

> test4:= proc(x::evaln,y::evaln) local i;
for i from 1 to 2 do assign(args[i],i) od
end:

> test4(u,v):
u,v;

1, 2

However, LOC can't be used in the same way. You can define your own variable to stand for the sequence of local variables you want to index.

> test5:= proc() local x1, x2, i, locals;
locals:= x1,x2;
for i from 1 to 2 do assign(locals[i],i) od;
x1,x2;
end:

> test5();

1, 2

See also: || , args , assign , evaln , parameter , procedure

Maple Advisor Database R. Israel, 2000