Skip to content
LumenaryAcademy
Practice 60 min

Procedures and modules

Functions and subroutines with declared intents, pure, elemental and recursive procedures, optional and keyword arguments, and modules that organise code and give it safe interfaces.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

Small pieces with clear contracts

A numerical program of any size is built from small, testable pieces: a routine that computes forces, one that advances the state by a time step, one that writes output. Fortran calls these pieces procedures, and it is unusually explicit about their contracts. Each argument can be declared as input only, output only, or both. A procedure can promise to have no side effects. And when procedures live in modules, the compiler checks every call against the definition: the number of arguments, their types, their ranks and their intents.

That checking is the main reason to put every procedure in a module, which is what modern Fortran programmers do. In FORTRAN 77, procedures were compiled separately with no knowledge of each other, and calling one with the wrong arguments silently corrupted memory. This lesson covers procedures first, then modules, then the handful of behaviours that surprise people coming from other languages.

DefinitionsH

Functions and subroutines

Definition— Function, subroutine, intent

A function returns a value and is used inside expressions. A subroutine returns nothing directly and is invoked with call; it communicates through its arguments. Each dummy argument may declare an intent: intent(in) (the procedure only reads it), intent(out) (the procedure sets it, and its value on entry is undefined) or intent(inout) (both).

fortran
! Functions and subroutines, with intents, pure, elemental, recursive and optional arguments
program procedures
  implicit none
  real :: celsius(4) = [-10.0, 0.0, 37.0, 100.0]
  real :: lo, hi

  print '(a, f6.2)', 'diagonal of a 3 by 4 rectangle: ', diagonal(3.0, 4.0)
  print '(a, 4f7.1)', 'in Fahrenheit:', to_fahrenheit(celsius)       ! elemental: works on arrays
  call min_max(celsius, lo, hi)
  print '(a, 2f7.1)', 'min and max:  ', lo, hi
  print '(a, i0)', 'gcd(1071, 462) = ', gcd(1071, 462)
  print '(a, f8.2)', 'compound, default rate: ', compound(1000.0, 10)
  print '(a, f8.2)', 'compound, rate 0.08:    ', compound(1000.0, 10, rate=0.08)
  print '(a, f8.2)', 'keywords in any order:  ', compound(years=10, principal=1000.0)

contains

  ! A pure function: no side effects, result depends only on the arguments
  pure function diagonal(a, b) result(c)
    real, intent(in) :: a, b
    real :: c
    c = sqrt(a**2 + b**2)
  end function diagonal

  ! An elemental function is written for scalars but applies to arrays element by element
  elemental function to_fahrenheit(c) result(f)
    real, intent(in) :: c
    real :: f
    f = c * 9.0 / 5.0 + 32.0
  end function to_fahrenheit

  ! A subroutine returns results through intent(out) arguments
  subroutine min_max(x, smallest, largest)
    real, intent(in) :: x(:)                  ! assumed shape: the size comes with the array
    real, intent(out) :: smallest, largest
    smallest = minval(x)
    largest = maxval(x)
  end subroutine min_max

  ! Euclid's algorithm, recursively
  recursive function gcd(a, b) result(g)
    integer, intent(in) :: a, b
    integer :: g
    if (b == 0) then
       g = a
    else
       g = gcd(b, mod(a, b))
    end if
  end function gcd

  ! An optional argument with a default supplied in the body
  function compound(principal, years, rate) result(total)
    real, intent(in) :: principal
    integer, intent(in) :: years
    real, intent(in), optional :: rate
    real :: total, r
    r = 0.05
    if (present(rate)) r = rate
    total = principal * (1.0 + r)**years
  end function compound

end program procedures

It prints:

text
diagonal of a 3 by 4 rectangle:   5.00
in Fahrenheit:   14.0   32.0   98.6  212.0
min and max:    -10.0  100.0
gcd(1071, 462) = 21
compound, default rate:  1628.89
compound, rate 0.08:     2158.93
keywords in any order:   1628.89
  • contains. Procedures written after contains inside a program are internal procedures: they can see the program's variables and the compiler knows their interfaces. Lesson-sized programs can use them; real code puts procedures in modules.
  • result(c) names the variable that holds a function's result. Without it, the result variable has the function's own name. Using result is clearer and is required for recursive functions in older standards.
  • pure promises that the function has no side effects: it does not modify its arguments or global variables, and does no I/O. The compiler checks the promise, and pure procedures can be used in parallel constructs such as do concurrent (lesson 7).
  • elemental procedures are written for scalars and automatically apply element by element to arrays of any shape, just like the intrinsic sin. to_fahrenheit(celsius) converted all four values. Elemental procedures are pure by default.
  • Assumed-shape arrays. real, intent(in) :: x(:) accepts an array of any size, and the size travels with it, available through size(x).
  • recursive allows a procedure to call itself, as Euclid's algorithm does. Fortran 2018 made procedures recursive by default, but compilers have been slow to change their behaviour, so writing recursive explicitly is still the portable choice.
  • Optional and keyword arguments. real, intent(in), optional :: rate may be omitted by the caller; present(rate) tells you whether it was passed. Any argument can be passed by name, as in compound(years=10, principal=1000.0), which makes calls with many arguments readable and order-independent.

Note that intent(in) arguments cannot be assigned to, so compound copies the rate into a local r before using it. Never read an optional argument that is not present: that is undefined behaviour, not zero.

Worked examplesH

Modules

Definition— Module

A module is a program unit that packages declarations (constants, variables, derived types, interfaces) and procedures, written after contains. Other program units gain access to it with use. Every procedure in a module has an explicit interface, so the compiler checks every call to it.

fortran
! A module groups related procedures and data, and controls what is visible outside.
module statistics
  implicit none
  private                                    ! everything is private unless listed below
  public :: mean, std_dev, describe

  ! A generic name: describe works for integer and real arrays
  interface describe
     module procedure describe_real, describe_int
  end interface describe

contains

  pure function mean(x) result(m)
    real, intent(in) :: x(:)
    real :: m
    m = sum(x) / size(x)
  end function mean

  pure function std_dev(x) result(s)
    real, intent(in) :: x(:)
    real :: s
    s = sqrt(sum(squared_deviations(x)) / (size(x) - 1))
  end function std_dev

  pure function squared_deviations(x) result(d)   ! a private helper
    real, intent(in) :: x(:)
    real :: d(size(x))                             ! an automatic array, sized from the argument
    d = (x - mean(x))**2
  end function squared_deviations

  subroutine describe_real(label, x)
    character(len=*), intent(in) :: label
    real, intent(in) :: x(:)
    print '(a, a, i0, a, f8.3, a, f8.3)', label, ': n = ', size(x), ', mean = ', mean(x), ', sd = ', std_dev(x)
  end subroutine describe_real

  subroutine describe_int(label, x)
    character(len=*), intent(in) :: label
    integer, intent(in) :: x(:)
    call describe_real(label, real(x))
  end subroutine describe_int

end module statistics

program use_statistics
  use statistics, only: describe, mean
  implicit none
  real :: heights_cm(6) = [162.0, 175.5, 158.0, 181.0, 169.5, 173.0]
  integer :: goals(5) = [0, 2, 1, 4, 1]

  call describe('heights', heights_cm)
  call describe('goals', goals)
  print '(a, f6.2)', 'mean of the first three heights: ', mean(heights_cm(1:3))
end program use_statistics

It prints:

text
heights: n = 6, mean =  169.833, sd =    8.583
goals: n = 5, mean =    1.600, sd =    1.517
mean of the first three heights: 165.17

The module shows the conventions of well-organised Fortran:

  • private by default, then a public list. Only mean, std_dev and describe are visible outside; squared_deviations is an internal helper that can change without affecting users. This is the module's interface, in the software-design sense.
  • use statistics, only: describe, mean imports just the names a program needs, which documents where each name comes from and avoids clashes. A name can also be renamed on import: use statistics, only: average => mean.
  • Generic interfaces. interface describe ... end interface makes one name refer to two specific procedures, describe_real and describe_int; the compiler picks the right one from the argument types at compile time. Intrinsics such as abs and sqrt are generic in the same way. The same mechanism defines operators for your own types, which lesson 6 uses.
  • Automatic arrays. Inside squared_deviations, real :: d(size(x)) is a local array whose size depends on the argument, created on entry and freed on exit.
  • character(len=*) declares a string argument that takes its length from whatever the caller passes.
  • Intrinsic modules. Some modules come with the compiler. use, intrinsic :: iso_fortran_env gives standard constants such as the kinds of 64-bit reals and the unit numbers of standard input and output, and iso_c_binding provides the types for talking to C. The word intrinsic makes sure you get the compiler's module and not a file of yours with the same name. The next lesson relies on the first; lesson 7 on the second.

Modules can also hold variables, which act as global state shared by everything that uses the module. They are occasionally useful (a table of physical constants, a logging unit number), but mutable global state makes programs hard to test and impossible to parallelise safely, so most experienced programmers keep module variables to constants and pass everything else as arguments.

Explicit interfaces, and why they matter

Assumed-shape arrays, optional and keyword arguments, and elemental procedures all require the caller to know the procedure's interface: the compiler must pass hidden information, such as an array's shape, that a FORTRAN 77-style call would not. Inside a module or after contains, the interface is known automatically. A procedure compiled separately outside any module (an external procedure) has an implicit interface, and calling it with the wrong argument types may compile without complaint and fail mysteriously at run time. When you must call external procedures, for example from an old library, declare their interfaces with an interface block. When you write new code, put it in modules and the problem disappears.

ComputationC

Procedures as arguments

Numerical libraries are full of routines that work on any function: integrators, root finders, optimisers, ODE solvers. In Fortran you pass the function itself as an argument, and an abstract interface describes what such a function must look like, so that the compiler can check every call.

fortran
! Passing procedures as arguments: one integration routine for any function
module integration
  implicit none
  private
  public :: integrand, simpson

  abstract interface                         ! the shape every integrand must have
     pure function integrand(x) result(y)
       real, intent(in) :: x
       real :: y
     end function integrand
  end interface

contains

  ! Composite Simpson's rule with n (even) subintervals
  function simpson(f, a, b, n) result(total)
    procedure(integrand) :: f
    real, intent(in) :: a, b
    integer, intent(in) :: n
    real :: total, h
    integer :: k
    h = (b - a) / n
    total = f(a) + f(b)
    do k = 1, n - 1
       total = total + merge(4.0, 2.0, mod(k, 2) == 1) * f(a + k * h)
    end do
    total = total * h / 3.0
  end function simpson

end module integration

module integrands
  implicit none
contains
  pure function parabola(x) result(y)
    real, intent(in) :: x
    real :: y
    y = x**2
  end function parabola

  pure function bell(x) result(y)
    real, intent(in) :: x
    real :: y
    y = exp(-x**2 / 2.0) / sqrt(2.0 * acos(-1.0))     ! the standard normal density
  end function bell
end module integrands

program integrate
  use integration, only: simpson
  use integrands, only: parabola, bell
  implicit none
  print '(a, f10.6)', 'integral of x**2 from 0 to 3:     ', simpson(parabola, 0.0, 3.0, 10)
  print '(a, f10.6)', 'area under the bell from -1 to 1: ', simpson(bell, -1.0, 1.0, 20)
  print '(a, f10.6)', 'sin from 0 to pi:                 ', simpson(sine, 0.0, acos(-1.0), 20)
contains
  pure function sine(x) result(y)            ! an internal procedure works too
    real, intent(in) :: x
    real :: y
    y = sin(x)
  end function sine
end program integrate

It prints:

text
integral of x**2 from 0 to 3:       9.000001
area under the bell from -1 to 1:   0.682690
sin from 0 to pi:                   2.000007
  • abstract interface declares a procedure shape, here "a pure function taking one real and returning a real", without defining any procedure. It works like a type for functions.
  • procedure(integrand) :: f declares a dummy argument that must be a procedure with that shape. Inside simpson, f(a) calls whatever function the caller passed.
  • Any matching procedure can be passed: module procedures such as parabola and bell, and since Fortran 2008 also internal procedures such as sine. Passing a function with the wrong signature is a compile-time error.
  • merge(4.0, 2.0, mod(k, 2) == 1) picks Simpson's weights, 4 for odd interior points and 2 for even ones, without an if.

The results are close to the exact values, 9, about 0.682689 (the probability that a normally distributed quantity lies within one standard deviation of its mean) and 2; the small errors in the last digits come from single-precision arithmetic, not from Simpson's rule, which is exact for polynomials up to degree three. The next lesson fixes the precision. The same mechanism also gives procedure pointers, variables that hold a procedure and can be reassigned at run time, declared as procedure(integrand), pointer :: g => null(), and type-bound procedures, which lesson 6 uses for object-oriented code.

Common misconceptionsH

Surprises in arguments and locals

Three behaviours catch almost everyone at least once. This program shows all three:

fortran
! Three behaviours of procedure arguments and locals that surprise newcomers
program surprises
  implicit none
  real :: data(0:4) = [10.0, 20.0, 30.0, 40.0, 50.0]
  integer :: k

  ! 1. An initialised local variable is saved between calls
  do k = 1, 3
     call count_calls()
  end do

  ! 2. Inside a procedure, an assumed-shape array starts at index 1
  call show_bounds(data)

  ! 3. Arguments are passed by reference: the procedure changes the caller's variable
  call double_it(data(2))
  print '(a, 5f6.1)', 'after double_it(data(2)): ', data

contains

  subroutine count_calls()
    integer :: calls = 0                     ! implies save: set to 0 once, not on every call
    calls = calls + 1
    print '(a, i0, a)', 'count_calls has been called ', calls, ' time(s)'
  end subroutine count_calls

  subroutine show_bounds(x)
    real, intent(in) :: x(:)
    print '(a, i0, a, i0, a, f5.1)', 'inside: bounds ', lbound(x, 1), ':', ubound(x, 1), ', x(1) = ', x(1)
  end subroutine show_bounds

  subroutine double_it(v)
    real, intent(inout) :: v
    v = 2.0 * v
  end subroutine double_it

end program surprises

It prints:

text
count_calls has been called 1 time(s)
count_calls has been called 2 time(s)
count_calls has been called 3 time(s)
inside: bounds 1:5, x(1) =  10.0
after double_it(data(2)):   10.0  20.0  60.0  40.0  50.0

Misconception

"integer :: calls = 0 sets calls to zero on every call." An initialisation in a declaration happens once, and it gives the variable the save attribute, so it keeps its value between calls, as the counter shows. Sometimes that is what you want (and then it is clearer to write integer, save :: calls = 0), but more often it is a bug: a variable meant to be reset quietly accumulates. To reset each time, declare integer :: calls and assign calls = 0 as the first executable statement.

Misconception

"An array keeps its bounds when passed to a procedure." The caller's data has bounds 0 to 4, but the assumed-shape dummy x(:) has bounds 1 to 5: x(1) is the caller's data(0). Only the shape is passed, not the bounds. If the bounds matter, declare them, as in real, intent(in) :: x(0:), or pass them explicitly.

Misconception

"Arguments are copies." Fortran passes arguments by reference (or behaves as if it did): double_it(data(2)) doubled the caller's element. That is why intents matter. They document and enforce which arguments a procedure may change, and they let the compiler optimise, because an intent(in) argument is known not to change.

Misconception

"Two arguments can refer to the same variable." If you pass the same variable as two arguments and the procedure modifies one of them, the program is not standard-conforming, and the compiler is entitled to assume it never happens. This no-aliasing rule is one reason Fortran compilers optimise loops so well, and C needed the later restrict keyword to catch up.

Misconception

"A function in an expression is always called." The standard lets the compiler skip evaluating any part of an expression whose value is not needed, so in if (x > 0.0 .or. check(y)) the function check may or may not run, and in f(x) + f(x) it may run once. A function that prints, counts or changes a module variable can therefore behave differently from one compiler, or optimisation level, to the next. Keep functions free of side effects, ideally pure, and use subroutines for anything that must happen.

ExplanationH

How professional Fortran code is organised

A typical modern research code has one main program of a few dozen lines and dozens of modules, each in its own file, roughly one per concept: constants.f90, grid.f90, physics.f90, io.f90. Modules use each other in a hierarchy without cycles, because the compiler must compile a module before any file that uses it. Large modules can be split with submodules (Fortran 2008), which put the implementations of procedures in separate files from their interfaces, so changing an implementation does not force everything that uses the module to recompile.

A submodule looks like this. The parent module declares only the interface, with module function inside an interface block:

fortran
module geometry
  implicit none
  interface
     module function polygon_area(x, y) result(area)
       real, intent(in) :: x(:), y(:)
       real :: area
     end function polygon_area
  end interface
end module geometry

submodule (geometry) geometry_impl
contains
  module procedure polygon_area                   ! the shoelace formula
    area = 0.5 * abs(sum(x * cshift(y, 1)) - sum(y * cshift(x, 1)))
  end procedure polygon_area
end submodule geometry_impl

Code that uses geometry sees only the interface; the formula lives in geometry_impl, which can be edited and recompiled on its own. In a code with hundreds of modules, this can turn a twenty-minute rebuild into a few seconds.

Some further habits are almost universal: every argument has an intent; procedures are pure whenever they can be; functions do not change their arguments (use a subroutine if you need to return several values or modify data); names say what things are (time_step, not dt2); and precision is chosen in one place, a kinds or constants module, which the next lesson builds.

Exercises

Exercises

1. Procedures and modules

CoreComputational

What does this program print?

program e1
  implicit none
  integer :: k, n
  do k = 1, 4
     n = tally()
  end do
  print '(i0)', n
contains
  integer function tally()
    integer :: count = 10
    count = count + 1
    tally = count
  end function tally
end program e1

2. Procedures and modules

CoreComputational

The caller declares real :: v(-2:2) = [1., 2., 3., 4., 5.] and passes v to

real function first(x)
  real, intent(in) :: x(:)
  first = x(1)
end function first

What does print '(f0.1)', first(v) print?

3. Procedures and modules

Warm-upComputational

Given elemental real function square(x) returning x * x, what does print '(*(f0.1, 1x))', square([1.0, 2.0, 3.0]) print?

4. Procedures and modules

Warm-upComputational

A recursive function returns 1 for n <= 1 and n * f(n - 1) otherwise. What is f(4)?

5. Procedures and modules

CoreComputational

A function stretch(x, by) has an optional argument by; it returns x * by if by is present and x * 2.0 otherwise. What does print '(f0.1)', stretch(2.0) + stretch(2.0, by=3.0) print?

6. Procedures and modules

CoreHuman

A subroutine declares real, intent(out) :: result. What may the subroutine assume about result when it starts?

Choose one

7. Procedures and modules

CoreHuman

Which are benefits of putting procedures in modules rather than writing them as external procedures? Select all that apply.

Choose all that apply

8. Procedures and modules

Warm-upComputational

A program contains use statistics, only: describe, mean. The module also has a public function std_dev. Can the program call std_dev?

Choose one

Further reading and resources