next up previous contents
Next: Modifying the Value of Up: Scoping Rules Previous: Examing Global Variables from

Modifying Global Variables

Suppose we would like our routine to modify a global variable. Consider the following variable SmallestSoFar and procedure FindMinimum.
> SmallestSoFar := 10^90;                  # effectively infinity
> FindMinimum := proc(L : list)
>   for i from 1 to length(L) do
>     if (L[i]<SmallestSoFar) then
>       SmallestSoFar := L[i];
>     fi;
>   od;
> end:
Since SmallestSoFar is assigned 1090 outside of FindMinimum, it is a global variable to procedure FindMinimum. By default, we can not change SmallestSoFar inside of FindMinimum. Since SmallestSoFar participates in the left hand side of an assignment, Darwin creates a new local variable SmallestSoFar. Executing this program in its current form results in a values cannot be ordered error since Darwin does not know how to compare the element L[i] with the uninitialized name SmallestSoFar when i=1. To extend the scope of SmallestSoFar to include FindMinimum we use the global statement after the proc declaration.
> FindMinimum := proc(L : list)
>   global SmallestSoFar;
    (as before)

> end;
Now any change made to SmallestSoFar persists after the end of the FindMinimum procedure.
> print(SmallestSoFar);
> FindMinimum([89, 100, 2, 77, 33]);
> print(SmallestSoFar);

Gaston Gonnet