Example 1
Create a procedure that uses a for loop to find the sum of the first 4 powers of the input:
>
|
powersofanumber := proc(n) for i to 4 do print(n^i); end do; end proc;
|
| (2.1) |
Since a variable (i) is used in the procedure and not declared as either global or local, it is implicitly declared local. To avoid this message, make a local variable declaration explicitly.
Solution 1:
Use a local variable declaration. For more about this, see procedure.
>
|
powersofanumber := proc(n) local i; for i to 4 do n^i; end do; end proc;
|
| (2.3) |
Solution 2:
You can declare a variable as local right where it is used. In this case, since i is used in the loop, you can declare i local in the loop control clause:
>
|
powersofanumber := proc(n) for local i to 4 do n^i; end do; end proc;
|
| (2.4) |
For more about this, see local_scopes.
Example 2
Create a procedure that increments . For example, can be a global counter that increments every time is called.
>
|
f:=proc(a) x:=x+a end proc;
|
| (2.6) |
Call .
Note that did not change.
Solution:
In this example, to use to modify the global variable , must be declared global.
>
|
f:=proc(a) local x; x:=x+a end proc;
|
| (2.11) |
Call .
Note that changes.
Example 3
In the following function, defined with an arrow, an indexing variable is used (j).
| (2.14) |
Solution
To avoid seeing the warning message, declare j as a local variable.
| (2.15) |
For introductory information on functions defined using arrows, see Functional Operators.