How to resolve the algorithm Apply a callback to an array step by step in the Oberon-2 programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Apply a callback to an array step by step in the Oberon-2 programming language

Table of Contents

Problem Statement

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

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Apply a callback to an array step by step in the Oberon-2 programming language

Source code in the oberon-2 programming language

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.

  

You may also check:How to resolve the algorithm Pig the dice game step by step in the Wren programming language
You may also check:How to resolve the algorithm Caesar cipher step by step in the Objeck programming language
You may also check:How to resolve the algorithm Program termination step by step in the Transd programming language
You may also check:How to resolve the algorithm Jacobsthal numbers step by step in the Quackery programming language
You may also check:How to resolve the algorithm Pseudo-random numbers/Splitmix64 step by step in the Java programming language