Regular versus recursive functions in Fortran
This is a short post that contrasts recursive versus regular Fortran functions and gives an example factorial $n!$ recursive function.
Basics of a Fortran function
In Fortran, unlike many other languages, a user-defined function can only calculate a single value such as an integer, an array, or a character string. Also, the name of the function should also be the name of the value that it calculates by assigning it somewhere inside the function (see example below). Lastly, a return statement is not needed in a Fortran function unless the end of the function is always reached every time it is invoked.
function add(num1, num2) ! a regular function that adds two numbers implicit none intent(in) :: num1, num2 real :: num1, num2, add !the function name "add" must be assigned to the return value add = num1 + num2 end function add
What makes a recursive Fortran function different?
Recursive functions were added to Fortran 90 and later versions. The main syntactical difference with normal Fortran functions is the intrinsic "recursive" declaration and "result()" assignment that both go in the function declaration line. For example, using the factorial as an example:
recursive function factorial(n) result(fact) implicit none intent(in) :: n integer (kind=8):: fact, n
if (n == 0) then fact = 1 else fact = n * factorial(n-1) endif
end function factorial
program fact implicit none integer :: n, factorial
print *, "Enter a positive integer: " read (*,*) n print *, 'factorial = ', factorial(n)
end program fact
Post a Comment