Download Maple Programming Guide - Numerical Relativity Group at UBC

Transcript
232 • 6 Procedures
every element has been divided by the element with the largest magnitude, and then raised
to a specified integer power:
> PowerList := proc( L::list, power::integer )
local largest := max(abs~(L));
map( proc(x) (x / largest) ^ power end proc, L )
end proc:
> PowerList([1,1/2,-3.14],2);
(6.43)
This example uses an anonymous nested procedure, declared directly within the expression
that uses it. Notice that this inner procedure refers to both of the symbols power and largest.
Because there are no variable or parameter declarations in the inner procedure that declare
these symbols, lexical scoping ensures that they are automatically bound to the corresponding
symbol in the outer procedure. In other words, power in the inner procedure refers to the
parameter power of the outer procedure, and largest in the inner procedure refers to the
local variable largest of the outer procedure.
Scoping Rules
If you want a variable to be local to a procedure or global, you should declare that variable
using a local or global declaration. Declaring the scope of variables makes it easier to debug
your code, and also makes it easier for someone else to understand your procedure.
On the other hand, if a variable is intended to refer to a parameter or local variable declared
in an enclosing procedure, you must not declare it in the enclosed procedure. Doing so
would defeat lexical scoping by making the variable local to the enclosed procedure, and
thus a different variable with no connection to the one in the enclosing procedure.
If an undeclared variable does not correspond to a parameter or declared variable in a surrounding procedure, Maple determines its scope, and either automatically declare the variable
as local or assume that it is global. When the variable is automatically declared local, such
an implicit declaration generates a warning:
> ImplicitLocal := proc( x, y )
z := x + y;
if z < 0 then z^2 else z^3 end if
end proc:
Warning, `z` is implicitly declared local to procedure `ImplicitLocal`