TExcelTAD
Home › Fortran › Fortran Pure & Elemental

Fortran Pure & Elemental

Fortran lets you make promises about your procedures that the compiler checks and the optimiser exploits. The two most useful are pure (no side effects) and elemental (works element by element on arrays of any shape).

pure procedures

A pure procedure has no side effects. The compiler enforces rules such as:

  • all function arguments must be intent(in) (subroutine arguments need an intent);
  • no modification of module or host variables;
  • no I/O (no print, no write to files);
  • no saved local variables and no stop;
  • only other pure procedures may be called.
fortran · try it yourself
module conversions
  implicit none
contains

  pure function celsius_to_kelvin(c) result(k)
    real, intent(in) :: c
    real :: k
    k = c + 273.15
  end function celsius_to_kelvin

  pure subroutine min_max(x, lo, hi)
    real, intent(in) :: x(:)
    real, intent(out) :: lo, hi
    lo = minval(x)
    hi = maxval(x)
  end subroutine min_max

end module conversions

program use_pure
  use conversions
  implicit none
  real :: lo, hi
  print '(f8.2)', celsius_to_kelvin(25.0)
  call min_max([3.5, -1.0, 8.25], lo, hi)
  print '(2f8.2)', lo, hi
end program use_pure
  298.15
   -1.00    8.25

Why bother? Pure procedures are easier to test and reason about (same input, same output), they are required inside do concurrent loops and forall, and they allow the compiler to reorder, vectorise or parallelise calls safely.

If you break a rule, the compiler tells you:

fortran · try it yourself
module bad_pure
  implicit none
  integer :: call_count = 0
contains
  pure function double_it(x) result(y)
    real, intent(in) :: x
    real :: y
    call_count = call_count + 1     ! modifies a module variable
    y = 2.0 * x
  end function double_it
end module bad_pure

program main
  use bad_pure
  implicit none
  print *, double_it(1.0)
end program main
/app/example.f90:8:5:

    8 |     call_count = call_count + 1     ! modifies a module variable
      |     1~~~~~~~~~~
Error: Variable 'call_count' cannot appear in a variable definition context (assignment) at (1) in PURE procedure
/app/example.f90:14:7:

   14 |   use bad_pure
      |       1
Fatal Error: Cannot open module file 'bad_pure.mod' for reading at (1): No such file or directory
compilation terminated.

The first error is the real one; the second only says that, because the module failed to compile, its .mod file was never written.

elemental procedures

An elemental procedure is written for scalar arguments but can be called with arrays of any shape. It is then applied to each element, just like the intrinsic sqrt or abs. Elemental procedures are automatically pure.

fortran · try it yourself
module grading
  implicit none
contains

  elemental function letter(score) result(g)
    integer, intent(in) :: score
    character :: g
    select case (score)
    case (90:)
      g = 'A'
    case (80:89)
      g = 'B'
    case (70:79)
      g = 'C'
    case default
      g = 'F'
    end select
  end function letter

  elemental function clamp(x, lo, hi) result(y)
    real, intent(in) :: x, lo, hi
    real :: y
    y = max(lo, min(hi, x))
  end function clamp

end module grading

program use_elemental
  use grading
  implicit none
  integer :: scores(6) = [95, 72, 88, 61, 79, 100]
  real :: m(2, 3)

  print '(a)', letter(85)                      ! scalar call
  print '(6(a, 1x))', letter(scores)           ! array call: one grade per score

  m = reshape([-2.0, 0.5, 1.5, 3.0, -0.1, 0.9], [2, 3])
  m = clamp(m, 0.0, 1.0)                       ! works on a 2-D array too
  print '(3f6.2)', m(1, :)
  print '(3f6.2)', m(2, :)
end program use_elemental
B
A C B F C A
  0.00  1.00  0.00
  0.50  1.00  0.90

The scalar arguments lo and hi are combined with every element of the array m. When several arguments are arrays, they must have the same shape and are processed element by element together.

Elemental subroutines

Subroutines can be elemental too. Here one call converts whole arrays of polar coordinates:

fortran · try it yourself
module coords
  implicit none
contains
  elemental subroutine polar_to_cartesian(r, theta, x, y)
    real, intent(in) :: r, theta
    real, intent(out) :: x, y
    x = r * cos(theta)
    y = r * sin(theta)
  end subroutine polar_to_cartesian
end module coords

program use_coords
  use coords
  implicit none
  real, parameter :: pi = 3.14159265
  real :: r(4) = 2.0
  real :: theta(4) = [0.0, pi / 2, pi, 3 * pi / 2]
  real :: x(4), y(4)
  integer :: i

  call polar_to_cartesian(r, theta, x, y)
  do i = 1, 4
    print '(2f7.3)', x(i), y(i)
  end do
end program use_coords
  2.000  0.000
 -0.000  2.000
 -2.000 -0.000
  0.000 -2.000

Notice the -0.000 values: cos(π/2) is not exactly zero in floating point but a tiny negative or positive number, which rounds to zero with a sign. When printing results for people you may want to add 0.0 or clean such values.

impure elemental

Occasionally you want element-wise behaviour with side effects, such as printing each element. Fortran 2008 allows impure elemental for that. It is rarer; reach for plain elemental first.

Test yourself

Which of these is NOT allowed in a pure function?

  1. Local variables
  2. Calling sqrt
  3. A print statement
  4. An if construct

What does calling an elemental function with a 3×3 array return?

  1. A scalar
  2. A 3×3 array with the function applied to each element
  3. A 9-element vector
  4. A compile error

Why are pure procedures useful for performance?

  1. They are compiled twice
  2. Without side effects, the compiler can safely reorder, vectorise or parallelise calls
  3. They use less memory
  4. They skip type checks