Task

Take a combined set of elements and apply a function to each element.




MODULE Callback EXPORTS Main;
 
IMPORT IO, Fmt;
 
TYPE CallBack = PROCEDURE (a: CARDINAL; b: INTEGER);
     Values = REF ARRAY OF INTEGER;
 
VAR sample := ARRAY [1..5] OF INTEGER {5, 4, 3, 2, 1};
    callback := Display;
 
PROCEDURE Display(loc: CARDINAL; val: INTEGER) =
  BEGIN
    IO.Put("array[" & Fmt.Int(loc) & "] = " & Fmt.Int(val * val) & "\n");
  END Display;
 
PROCEDURE Map(VAR values: ARRAY OF INTEGER; size: CARDINAL; worker: CallBack) =
  VAR lvalues := NEW(Values, size);
  BEGIN
    FOR i := FIRST(lvalues^) TO LAST(lvalues^) DO
      worker(i, values[i]);
    END;
  END Map;
 
BEGIN
  Map(sample, NUMBER(sample), callback);
END Callback.