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.
To compile and run this Fortran program:
In Fortran, we use a module to encapsulate the closure-like behavior. The int_seq function returns a pointer to a function, which is our way of implementing a closure. The internal function increment acts as the anonymous function in the original example.
The contains keyword in Fortran allows us to define internal procedures, which can access variables from their containing scope, similar to closures in other languages.
The abstract interface at the end defines the function type we use for our function pointers.
While Fortran doesn’t have true anonymous functions or closures in the same way as some other languages, this approach provides similar functionality.
The last feature of functions we’ll look at for now is recursion, which Fortran fully supports.