ZetCode

Modula-2 procedure types

last modified November 27, 2026 Modula-2

In Modula-2 a procedure is a value that can be stored and passed on. A procedure type describes the parameters and the result of a procedure; a variable of that type holds any procedure with a matching heading, and a call through the variable runs the procedure it holds. This lets a program choose at run time what to do, and lets a procedure take another procedure as a parameter.

A procedure variable

A procedure type is written like a procedure heading without the names: PROCEDURE (INTEGER, INTEGER): INTEGER is the type of functions that take two integers and return one. The parameter types are listed, the parameter names are not.

ops.mod
MODULE ops;

FROM InOut IMPORT WriteString, WriteLn, WriteInt;

TYPE
  Operation = PROCEDURE (INTEGER, INTEGER): INTEGER;

VAR
  op: Operation;

PROCEDURE Add(a, b: INTEGER): INTEGER;
BEGIN
  RETURN a + b
END Add;

PROCEDURE Multiply(a, b: INTEGER): INTEGER;
BEGIN
  RETURN a * b
END Multiply;

BEGIN
  op := Add;
  WriteString("op(6, 7) = ");
  WriteInt(op(6, 7), 0);
  WriteLn;
  op := Multiply;
  WriteString("op(6, 7) = ");
  WriteInt(op(6, 7), 0);
  WriteLn
END ops.

op := Add assigns the procedure itself; there are no parentheses after Add, because it is not called. op(6, 7) then calls whatever procedure op holds, first Add and then Multiply.

$ gm2 ops.mod -o ops
$ ./ops
op(6, 7) = 13
op(6, 7) = 42

The PROC type

The standard type PROC is the type of proper procedures without parameters. It needs no declaration.

greeting.mod
MODULE greeting;

FROM InOut IMPORT WriteString, WriteLn, WriteCard;

VAR
  greet: PROC;
  hour: CARDINAL;

PROCEDURE Morning;
BEGIN
  WriteString("Good morning")
END Morning;

PROCEDURE Evening;
BEGIN
  WriteString("Good evening")
END Evening;

BEGIN
  FOR hour := 8 TO 20 BY 6 DO
    IF hour < 12 THEN
      greet := Morning
    ELSE
      greet := Evening
    END;
    WriteCard(hour, 2);
    WriteString(":00  ");
    greet;
    WriteLn
  END
END greeting.

The loop chooses the procedure for each hour and stores it in greet. The statement greet alone calls it, as a call of a parameterless procedure is written.

$ gm2 greeting.mod -o greeting
$ ./greeting
 8:00  Good morning
14:00  Good evening
20:00  Good evening

Procedures as parameters

A parameter of a procedure type receives a procedure. The called procedure does its own work and calls the parameter where the caller's part is needed, a pattern called a callback.

tabulate.mod
MODULE tabulate;

FROM InOut IMPORT WriteString, WriteLn;
FROM RealInOut IMPORT WriteReal;
FROM MathLib0 IMPORT sqrt, sin;

TYPE
  Function = PROCEDURE (REAL): REAL;

PROCEDURE Half(x: REAL): REAL;
BEGIN
  RETURN x / 2.0
END Half;

PROCEDURE Table(name: ARRAY OF CHAR; f: Function; from, to, step: REAL);
VAR
  x: REAL;
BEGIN
  WriteString(name);
  WriteLn;
  x := from;
  WHILE x <= to DO
    WriteReal(x, 10);
    WriteReal(f(x), 12);
    WriteLn;
    x := x + step
  END
END Table;

BEGIN
  Table("half", Half, 1.0, 3.0, 1.0);
  Table("sqrt", sqrt, 0.0, 4.0, 2.0);
  Table("sin", sin, 0.0, 1.5, 0.5)
END tabulate.

Table prints a table of any function of type Function. It is called with the program's own Half and with sqrt and sin from MathLib0, whose headings match the type.

$ gm2 tabulate.mod -o tabulate
$ ./tabulate
half
  1.000000    0.500000
  2.000000    1.000000
  3.000000    1.500000
sqrt
  0.000000    0.000000
  2.000000    1.414214
  4.000000    2.000000
sin
  0.000000    0.000000
  0.500000    0.479426
  1.000000    0.841471
  1.500000    0.997495

What cannot be assigned

Only procedures declared at the outer level of a module can be assigned to a procedure variable. A nested procedure uses the variables of the procedure around it, which do not exist after that procedure returns. The standard procedures, such as ABS and ODD, cannot be assigned either.

restrict.mod
MODULE restrict;

FROM InOut IMPORT WriteInt, WriteLn;

TYPE
  Function = PROCEDURE (INTEGER): INTEGER;

VAR
  f: Function;

PROCEDURE Outer(n: INTEGER): INTEGER;

  PROCEDURE Twice(k: INTEGER): INTEGER;
  BEGIN
    RETURN 2 * k
  END Twice;

BEGIN
  f := Twice;
  RETURN f(n)
END Outer;

BEGIN
  f := ABS;
  WriteInt(Outer(5), 0);
  WriteLn
END restrict.

The compiler rejects both assignments. To pass a nested computation, move the procedure to the outer level of the module; to pass ABS, wrap it in an ordinary function procedure.

$ gm2 restrict.mod -o restrict
restrict.mod:19:8: error: In procedure ‘Outer’: cannot call nested procedure ‘Twice’ indirectly as the outer scope will not be known
   19 |   f := Twice;
      |        ^~~~~
restrict.mod:24:8: error: In program module ‘restrict’: an assignment cannot assign a standard function procedure ‘ABS’
   24 |   f := ABS;
      |        ^~~

A table of procedures

Procedure values can be stored in arrays. An index then selects an operation, and procedure values can be compared with = and #.

dispatch.mod
MODULE dispatch;

FROM InOut IMPORT WriteString, WriteLn, WriteInt, Write;

TYPE
  Operation = PROCEDURE (INTEGER, INTEGER): INTEGER;

VAR
  table: ARRAY [0..3] OF Operation;
  symbol: ARRAY [0..3] OF CHAR;
  i: CARDINAL;

PROCEDURE Add(a, b: INTEGER): INTEGER;
BEGIN
  RETURN a + b
END Add;

PROCEDURE Subtract(a, b: INTEGER): INTEGER;
BEGIN
  RETURN a - b
END Subtract;

PROCEDURE Multiply(a, b: INTEGER): INTEGER;
BEGIN
  RETURN a * b
END Multiply;

PROCEDURE Power(a, b: INTEGER): INTEGER;
VAR
  r: INTEGER;
BEGIN
  r := 1;
  WHILE b > 0 DO
    r := r * a;
    DEC(b)
  END;
  RETURN r
END Power;

BEGIN
  table[0] := Add;       symbol[0] := '+';
  table[1] := Subtract;  symbol[1] := '-';
  table[2] := Multiply;  symbol[2] := '*';
  table[3] := Power;     symbol[3] := '^';
  FOR i := 0 TO 3 DO
    WriteString("5 ");
    Write(symbol[i]);
    WriteString(" 3 =");
    WriteInt(table[i](5, 3), 4);
    IF table[i] = Power THEN
      WriteString("  (repeated multiplication)")
    END;
    WriteLn
  END
END dispatch.

table[i](5, 3) selects a procedure from the array and calls it. The comparison table[i] = Power is true only for the element that holds Power. The array symbol holds the matching operator characters for the output.

$ gm2 dispatch.mod -o dispatch
$ ./dispatch
5 + 3 =   8
5 - 3 =   2
5 * 3 =  15
5 ^ 3 = 125  (repeated multiplication)

VAR parameters in procedure types

A procedure type lists VAR before a parameter type when the procedure changes its argument. Only procedures whose parameter is also a VAR parameter match the type.

actions.mod
MODULE actions;

FROM InOut IMPORT WriteString, WriteLn, WriteInt;

TYPE
  Action = PROCEDURE (VAR INTEGER);

VAR
  levels: ARRAY [1..6] OF INTEGER;

PROCEDURE Double(VAR x: INTEGER);
BEGIN
  x := 2 * x
END Double;

PROCEDURE Clamp(VAR x: INTEGER);
BEGIN
  IF x > 10 THEN
    x := 10
  ELSIF x < -10 THEN
    x := -10
  END
END Clamp;

PROCEDURE ForEach(VAR a: ARRAY OF INTEGER; act: Action);
VAR
  i: CARDINAL;
BEGIN
  FOR i := 0 TO HIGH(a) DO
    act(a[i])
  END
END ForEach;

PROCEDURE Show(a: ARRAY OF INTEGER);
VAR
  i: CARDINAL;
BEGIN
  FOR i := 0 TO HIGH(a) DO
    WriteInt(a[i], 4)
  END;
  WriteLn
END Show;

BEGIN
  levels[1] := 3;  levels[2] := -8;  levels[3] := 6;
  levels[4] := 1;  levels[5] := -2;  levels[6] := 9;
  Show(levels);
  ForEach(levels, Double);
  Show(levels);
  ForEach(levels, Clamp);
  Show(levels)
END actions.

ForEach passes every element of the array to the action, and the action changes the element in place. The same loop doubles all elements in one call and limits them to the range -10 to 10 in the next.

$ gm2 actions.mod -o actions
$ ./actions
   3  -8   6   1  -2   9
   6 -16  12   2  -4  18
   6 -10  10   2  -4  10

Sort comparators

A sort procedure needs to know which of two elements comes first. Passing that test as a procedure, a comparator, lets one sort procedure produce any order.

comparators.mod
MODULE comparators;

FROM InOut IMPORT WriteString, WriteLn, WriteInt;

TYPE
  Before = PROCEDURE (INTEGER, INTEGER): BOOLEAN;

VAR
  data: ARRAY [0..6] OF INTEGER;

PROCEDURE Ascending(a, b: INTEGER): BOOLEAN;
BEGIN
  RETURN a < b
END Ascending;

PROCEDURE Descending(a, b: INTEGER): BOOLEAN;
BEGIN
  RETURN a > b
END Descending;

PROCEDURE Closer(a, b: INTEGER): BOOLEAN;
BEGIN
  RETURN ABS(a) < ABS(b)
END Closer;

PROCEDURE Sort(VAR a: ARRAY OF INTEGER; before: Before);
VAR
  i, j: CARDINAL;
  key: INTEGER;
BEGIN
  FOR i := 1 TO HIGH(a) DO
    key := a[i];
    j := i;
    WHILE (j > 0) AND before(key, a[j - 1]) DO
      a[j] := a[j - 1];
      DEC(j)
    END;
    a[j] := key
  END
END Sort;

PROCEDURE Show(label: ARRAY OF CHAR; a: ARRAY OF INTEGER);
VAR
  i: CARDINAL;
BEGIN
  WriteString(label);
  FOR i := 0 TO HIGH(a) DO
    WriteInt(a[i], 4)
  END;
  WriteLn
END Show;

BEGIN
  data[0] := 7;  data[1] := -3;  data[2] := 12;  data[3] := 0;
  data[4] := -9; data[5] := 4;   data[6] := -1;
  Sort(data, Ascending);
  Show("ascending: ", data);
  Sort(data, Descending);
  Show("descending:", data);
  Sort(data, Closer);
  Show("by size:   ", data)
END comparators.

Sort is an insertion sort on an open array. It moves each element left while the comparator says it belongs before its neighbour. Ascending and Descending give the two numeric orders, and Closer orders the numbers by their distance from zero. The sorting article covers faster algorithms.

$ gm2 comparators.mod -o comparators
$ ./comparators
ascending:   -9  -3  -1   0   4   7  12
descending:  12   7   4   0  -1  -3  -9
by size:      0  -1  -3   4   7  -9  12

Finding roots

The bisection method finds a zero of a continuous function in an interval where the function changes sign. It halves the interval again and again and keeps the half in which the sign changes. Written with a procedure parameter, it solves any equation.

roots.mod
MODULE roots;

FROM InOut IMPORT WriteString, WriteLn;
FROM RealInOut IMPORT WriteReal;
FROM MathLib0 IMPORT cos, exp;

TYPE
  Function = PROCEDURE (REAL): REAL;

PROCEDURE Cubic(x: REAL): REAL;
BEGIN
  RETURN x * x * x - 2.0 * x - 5.0
END Cubic;

PROCEDURE Fixed(x: REAL): REAL;
BEGIN
  RETURN cos(x) - x
END Fixed;

PROCEDURE Decay(x: REAL): REAL;
BEGIN
  RETURN exp(-x) - 0.25
END Decay;

PROCEDURE Bisect(f: Function; low, high: REAL): REAL;
VAR
  mid: REAL;
BEGIN
  WHILE high - low > 0.000001 DO
    mid := (low + high) / 2.0;
    IF (f(low) < 0.0) = (f(mid) < 0.0) THEN
      low := mid
    ELSE
      high := mid
    END
  END;
  RETURN (low + high) / 2.0
END Bisect;

PROCEDURE Solve(name: ARRAY OF CHAR; f: Function; low, high: REAL);
VAR
  x: REAL;
BEGIN
  WriteString(name);
  IF (f(low) < 0.0) = (f(high) < 0.0) THEN
    WriteString(": no sign change in the interval")
  ELSE
    x := Bisect(f, low, high);
    WriteString(": x =");
    WriteReal(x, 10);
    WriteString(", f(x) =");
    WriteReal(f(x), 10)
  END;
  WriteLn
END Solve;

BEGIN
  Solve("x^3 - 2x - 5", Cubic, 2.0, 3.0);
  Solve("cos x - x   ", Fixed, 0.0, 1.0);
  Solve("e^-x - 1/4  ", Decay, 0.0, 5.0);
  Solve("e^-x - 1/4  ", Decay, 2.0, 5.0)
END roots.

Bisect compares the signs at the lower end and in the middle: when they agree, the zero lies in the upper half. It stops when the interval is shorter than one millionth. Solve first checks for a sign change, because without one the method has nothing to find, as the last call shows. The three functions find the real root of a cubic, the fixed point of the cosine and the value of ln 4.

$ gm2 roots.mod -o roots
$ ./roots
x^3 - 2x - 5: x =  2.094552, f(x) =  0.000001
cos x - x   : x =  0.739085, f(x) =  0.000001
e^-x - 1/4  : x =  1.386294, f(x) =  0.000000
e^-x - 1/4  : no sign change in the interval

Next steps

This article ends the part of the series on procedures and arrays. The next articles define new types: enumerations and subranges, sets, strings and records.

Source

The GNU Modula-2 manual

Modula-2 language reference at modula2.org

In this article we have declared procedure types in Modula-2, stored procedures in variables and arrays, used the standard type PROC, passed procedures as parameters, and written comparators and a root finder. The procedures article covers the procedures themselves, and the open arrays article the array parameters used by the callbacks.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Modula-2 tutorials.