Closures in COBOL

COBOL does not directly support anonymous functions or closures in the same way as more modern programming languages. However, we can simulate a similar behavior using nested programs and shared data items. Here’s an equivalent implementation:

       IDENTIFICATION DIVISION.
       PROGRAM-ID. MAIN-PROGRAM.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 NEXT-INT-FUNC PROCEDURE-POINTER.
       
       PROCEDURE DIVISION.
           CALL 'INT-SEQ' RETURNING NEXT-INT-FUNC
           
           CALL NEXT-INT-FUNC
           CALL NEXT-INT-FUNC
           CALL NEXT-INT-FUNC
           
           CALL 'INT-SEQ' RETURNING NEXT-INT-FUNC
           CALL NEXT-INT-FUNC
           
           STOP RUN.
       
       IDENTIFICATION DIVISION.
       PROGRAM-ID. INT-SEQ.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 I PIC 9(5) VALUE 0.
       
       LINKAGE SECTION.
       01 RETURN-INT PROCEDURE-POINTER.
       
       PROCEDURE DIVISION RETURNING RETURN-INT.
           SET RETURN-INT TO ENTRY 'NEXT-INT'
           EXIT PROGRAM.
       
       ENTRY 'NEXT-INT'.
           ADD 1 TO I
           DISPLAY I
           EXIT PROGRAM.

In this COBOL implementation, we create a nested program structure to simulate the closure behavior:

  1. The INT-SEQ program acts as our closure generator. It initializes a local variable I and returns a procedure pointer to the NEXT-INT entry point.

  2. The NEXT-INT entry point increments I and displays its value, simulating the behavior of the anonymous function in the original Go code.

  3. In the main program, we call INT-SEQ to get a procedure pointer, which we then call multiple times to see the effect of the “closure”.

  4. To demonstrate that the state is unique to each “closure”, we create a new one by calling INT-SEQ again and calling the returned function.

To run this COBOL program:

$ cobc -x closure_simulation.cob
$ ./closure_simulation
1
2
3
1

This output demonstrates that our COBOL program behaves similarly to the original Go program, maintaining separate state for each “closure”.

While COBOL doesn’t have built-in support for closures, this example shows how we can achieve similar functionality using nested programs and procedure pointers. This approach allows us to encapsulate state and behavior in a way that mimics closures in more modern programming languages.