Recursion in Co-array Fortran
module recursion_module
implicit none
contains
! This fact function calls itself until it reaches the
! base case of fact(0).
recursive function fact(n) result(res)
integer, intent(in) :: n
integer :: res
if (n == 0) then
res = 1
else
res = n * fact(n-1)
end if
end function fact
! Fibonacci function using recursion
recursive function fib(n) result(res)
integer, intent(in) :: n
integer :: res
if (n < 2) then
res = n
else
res = fib(n-1) + fib(n-2)
end if
end function fib
end module recursion_module
program main
use recursion_module
implicit none
print *, fact(7)
print *, fib(7)
end program main
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:
$ gfortran -coarray=single recursion.f90 -o recursion
$ ./recursion
5040
13
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.