Fortran Procedures - Functions and Subroutines Recursive Procedures


Example

In Fortran functions and subroutines need to be explicitly declared as recursive, if they are to call themselves again, directly or indirectly. Thus, a recursive implementation of the Fibonacci series could look like this:

recursive function fibonacci(term) result(fibo)
  integer, intent(in) :: term
  integer :: fibo

  if (term <= 1) then
    fibo = 1
  else
    fibo = fibonacci(term-1) + fibonacci(term-2)
  end if
  
end function fibonacci

Another example is allowed to calculate factorial:

recursive function factorial(n)  result(f)
  integer :: f
  integer, intent(in) :: n
  
  if(n == 0) then
    f = 1
  else
    f = n * f(n-1)
  end if
end function factorial

For a function to directly recursively reference itself its definition must use the result suffix. It is not possible for a function to be both recursive and elemental.