Previous Up Next

12.1.3  Local variables

Local variables in a function definition can be given initial values in the line they are declared in by putting their initialization in parentheses; for example,

local a,b;
a:= 1;

is the same as

local (a:= 1), b;

Local variables should be given values within the function definition. If you want to use a local variable as a symbolic variable, then you can indicate that with the assume command (see Section 5.4.8). For example, if you define a function myroots by

myroots (a):= {
local x;
return solve(x^2=a,x);
}

then calling

myroots(4)

will simply return the empty list. You could leave x undeclared, but that would make x a global variable and could interact with other functions in unexpected ways. You can get the behavior you probably expected by explicitly assuming x to be a symbol;

myroots (a):= {
local x;
assume(x,symbol);
return solve(x^2=a,x);
}

(Alternatively, you could use purge(x) instead of assume(x,symbol).) Now if you enter

myroots(4)

you will get

[−2,2]

Previous Up Next