Next: Variable Number of Arguments Up: Procedures Previous: The return Command

# Nested Routines

A procedure is nested if it is declared within the body of another procedure. The scoping rules for such procedures are the same as the scoping rules for local variables. The motivation for such constructs is similar to the motivation for local variables: if a routine is only used by one procedure, then it should not be visible to the remaining program. This results in easier to read code and less troublesome modifications. We present a simple example of a function VectorMean nested inside of a function VectorVariance but note that Darwin allows for an arbitrary depth of nesting.

```   VectorVariance := proc( M : array(real) )
local variance, mean;
variance := 0;

VectorMean := proc( M1 : array(real) )  # a nested function
local total;
total:=0;
for i from 1 to length(M1) do
total := total + M1[i];
od;
return(total/length(M1));
end;

mean := VectorMean(M);
for i from 1 to length(M) do
variance := variance + (M[i] - mean)^2;
od;
variance;
end;
```

The function VectorVariance calculates the variance for a linear array of real elements. In order to carry out this computation, it requires that the mean of the array is calculated. This is performed in the nested function VectorMean. This function accepts an array of real elements and returns a single real number to the function VectorVariance. Only the body of the function VectorVariance has access to this function.

```> VectorVariance([12, 6, 18, 13, 21, 7, 11, 12, 14]);
180.0000
```

Gaston Gonnet
1998-09-15