Co-array Fortran supports anonymous functions, which can form closures. Anonymous functions are useful when you want to define a function inline without having to name it.
In this Co-array Fortran version, we’ve implemented a similar concept of closures using a module and function pointers. The int_seq function returns a pointer to an internal function increment, which acts as our closure.
To run the program, save it as closures.f90 and compile it with a Co-array Fortran-compatible compiler:
The output demonstrates that the closure maintains its state between calls, and a new closure starts with a fresh state.
Note that Co-array Fortran doesn’t have built-in support for anonymous functions or closures in the same way as some other languages. This implementation uses function pointers and internal procedures to achieve similar functionality.
The last feature of functions we’ll look at for now is recursion, which is fully supported in Co-array Fortran.