We already know how to define functions in maple. However, all of the functions we have defined so far have consisted of a single maple expression (no matter how complicated it might be). For example,
> sqr := x -> sqrt(x);
> sqr(25);
However, maple has a more versatile way of defining functions using
the proc command. The function sqr2 below behaves
exactly the same as sqr defined above.
(When using proc, the function begins with the keyword
proc, followed by any parameters in parenthesis, then one or
more maple statements, and finally the keyword end. The result
of the function is the result of the last maple command executed.
> sqr2 := proc(x)
sqrt(x);
end;
> sqr2(25);
> sqr2(-25);
Unlike the functions defined by ->, however, we can use several
statements when using proc:
> sqr3 := proc(x)
if (x >= 0) then
sqrt(x);
else
print(`Square root of `,x,`is not a real number`);
fi;
end;
> sqr3(-25);
> sqr3(25);
Here is another variation on the same idea: we compute a variable y = x2. If y > 25, the result is 25, otherwise it is y. 3.7
> try:= proc(x)
y := x^2;
if ( y>25) then
25;
else
y;
fi;
end;
What does that warning mean? It means that maple has assumed that the
variable y used in try is local to that procedure.
That is, it is different from a variable y that may be used outside
the context of the procedure. Let's check that. First, we set
y to 35, invoke try(19) (which sets its copy of
y to 361), then check what the value of y is.
> y:=35;
> try(19);
> y;
It is still 35. Now, let's add a line saying that y has a
global definition-- the y within the procedure is the
same as the y outside.
> try2:= proc(x)
global y;
y := x^2;
if ( y>25) then
25;
else
y;
fi;
end;
> y;
> try2(19);
> y;
This time, of course, y was changed by invoking try2.
The opposite of global is, not surprisingly, local. In order
to stop maple from giving warnings about variables being implicitly
declared local, we can add a the statement local y;
just after the proc statement. Using such statements is called
``declaring'' the variables. This is a good habit to get into,
because it lessens the chance of accidentally using a global variable
or of misspelling the name of a variable. Some computer languages
require that you declare all variables you use.