Recursion in Co-array Fortran
Co-array Fortran supports recursive functions. Here’s a classic example implementing factorial and Fibonacci functions using recursion.
The fact
function calculates the factorial of a given number. It calls itself until it reaches the base case of fact(0)
.
For the Fibonacci sequence, we define a separate recursive function fib
. Unlike in some other languages, Fortran doesn’t have the concept of closures, so we implement it as a regular recursive function.
To run the program:
In this example, we calculate the factorial of 7 (which is 5040) and the 7th Fibonacci number (which is 13).
Note that while Co-array Fortran is an extension of Fortran designed for parallel programming, this example doesn’t utilize its parallel features. For more complex scenarios, you could leverage Co-array Fortran’s parallel capabilities to potentially optimize recursive algorithms across multiple images (the Co-array Fortran equivalent of processes).
When writing recursive functions in Fortran, it’s important to use the recursive
keyword before the function
keyword to explicitly allow recursion. This is a requirement in Fortran, unlike some other languages where recursion is implicitly allowed.