modula-2 home

  Home  
  Tutorial  
  Win32 API  
  Reference  
  Projects  
 

 

Type declarations

Procedure types

Procedure type objects have the addresses of procedures as values. Specify procedure types as follows:

PROCEDURE [(ParameterList) [: ReturnType] ]

 

ParameterList is:

[Parameter {,Parameter}]

 

Parameter is:

[VAR] [ARRAY OF {ARRAY OF}] TypeName

For detailed information on the VAR, INOUT, OUT, FAR, NEAR, VALUE and NOHIGH identifiers see the Procedures topic of this file.

ReturnType is the type of value returned by procedures.  It must be a type name and may be qualified by a module name.

Example:

TYPE Func = PROCEDURE(REAL) : REAL;

Variables of procedure types can be assigned the value of a procedure that has the same types of parameters and return value, and the same attributes.

Only procedures that are not contained in other procedures can be assigned as the values of procedure variables.  Standard procedures cannot be assigned as the values of procedure variables.

Using procedure types

Procedure types are often used as parameters to other procedures.  This is useful when the procedure specifies an algorithm that involves calling another procedure or function, and the called procedure or function varies from one call to the next.

A good example of the use of procedure types is a numeric integration procedure.  The procedure implements the algorithm of numeric integration but the function being integrated is passed in as a parameter:

PROCEDURE Integrate(X1, X2 : REAL;
   NumPoints : CARDINAL;
   Function : Func) : REAL;
VAR
   Sum : REAL;
   i   : CARDINAL;
   X, DX  : REAL;
BEGIN
   DX := (X2-X1)/FLOAT(NumPoints-1);
   X := X1;
   Sum := 0.0;
   FOR i := 1 TO NumPoints-1 DO
       Sum := Sum + Function(X) * DX;
       X := X + DX;
   END;
   RETURN Sum;
END Integrate;


Source:

  • Wirth N: Programming in Modula-2, 3rd ed. Springer Verlag, Berlin, 1985.
  • Stony Brook Modula-2 documentation. Used with permission. Note: Stony-Brook M2 offers an extended syntax with features not described here. Stony Brook M2 users are encouraged to visit the Stony Brook website and to consult the Stony Brook help system.