Task

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




 
MODULE ApplyCallBack;
IMPORT
  Out := NPCT:Console;
 
TYPE
  Fun = PROCEDURE (x: LONGINT): LONGINT;
  Ptr2Ary = POINTER TO ARRAY OF LONGINT;
 
VAR
  a: ARRAY 5 OF LONGINT;
  x: ARRAY 3 OF LONGINT;
  r: Ptr2Ary;
 
  PROCEDURE Min(x,y: LONGINT): LONGINT;
  BEGIN
    IF x <= y THEN RETURN x ELSE RETURN y END;
  END Min;
 
  PROCEDURE Init(VAR a: ARRAY OF LONGINT);
  BEGIN
    a[0] := 0;
    a[1] := 1;
    a[2] := 2;
    a[3] := 3;
    a[4] := 4;
  END Init;
 
  PROCEDURE Fun1(x: LONGINT): LONGINT;
  BEGIN
    RETURN x * 2
  END Fun1;
 
  PROCEDURE Fun2(x: LONGINT): LONGINT;
  BEGIN
    RETURN x DIV 2;
  END Fun2;
 
  PROCEDURE Fun3(x: LONGINT): LONGINT;
  BEGIN
    RETURN x + 3;
  END Fun3;
 
  PROCEDURE Map(F: Fun; VAR x: ARRAY OF LONGINT);
  VAR
    i: LONGINT;
  BEGIN 
    FOR i := 0 TO LEN(x) - 1 DO
      x[i] := F(x[i])
    END
  END Map;
 
  PROCEDURE Map2(F: Fun; a: ARRAY OF LONGINT; VAR r: ARRAY OF LONGINT);
  VAR
    i,l: LONGINT;
  BEGIN
    l := Min(LEN(a),LEN(x));
    FOR i := 0 TO l - 1 DO 
      r[i] := F(a[i])
    END
  END Map2;
 
  PROCEDURE Map3(F: Fun; a: ARRAY OF LONGINT): Ptr2Ary;
  VAR
    r: Ptr2Ary;
    i: LONGINT;
  BEGIN
    NEW(r,LEN(a));
    FOR i := 0 TO LEN(a) - 1 DO
      r[i] := F(a[i]);
    END;
    RETURN r
  END Map3;
 
  PROCEDURE Show(a: ARRAY OF LONGINT);
  VAR
    i: LONGINT;
  BEGIN
    FOR i := 0 TO LEN(a) - 1 DO
      Out.Int(a[i],4)
    END;
    Out.Ln
  END Show;
 
BEGIN
  Init(a);Map(Fun1,a);Show(a);
  Init(a);Map2(Fun2,a,x);Show(x);
  Init(a);r := Map3(Fun3,a);Show(r^);
END ApplyCallBack.
 