Recursion in Fortran

Our example demonstrates recursive functions in Fortran. Here’s a classic example.

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

In this Fortran version:

  1. We define a module recursion_module to contain our recursive functions.

  2. The fact function is defined as recursive. It calculates the factorial of a number using recursion.

  3. The fib function is also defined as recursive. It calculates the Fibonacci number using recursion.

  4. In the main program, we use the module and call both functions with an argument of 7.

To run the program, save it as recursion.f90 and compile it using a Fortran compiler:

$ gfortran recursion.f90 -o recursion
$ ./recursion
      5040
        13

Note that in Fortran, we use the recursive keyword to explicitly declare a function as recursive. Unlike Go, Fortran doesn’t have closures, so we implement the Fibonacci function as a separate recursive function rather than a closure.

Fortran’s strong typing and explicit recursion declarations make it well-suited for scientific and numerical computations where recursion might be used in complex algorithms.