TExcelTAD
Home › Fortran › Fortran Interfaces & Generics

Fortran Interfaces & Generics

An interface describes how a procedure is called: its name, arguments and result, without its body. Interfaces serve three purposes in modern Fortran: describing external procedures, declaring the type of procedure arguments, and, most usefully, creating generic names that work for several argument types.

Explicit interfaces

When the compiler knows a procedure's interface, it checks every call: number of arguments, their types, kinds and ranks. Module and internal procedures have an explicit interface automatically. A procedure compiled separately, outside any module (an external procedure), does not, so legacy code often describes it with an interface block:

fortran
interface
  function vector_norm(v, n) result(r)
    integer, intent(in) :: n
    real, intent(in) :: v(n)
    real :: r
  end function vector_norm
end interface

In new code, just put the procedure in a module. Interface blocks remain essential for the two uses below and for calling C (see the C interoperability lesson).

Generic procedures

A generic interface gives one name to several specific procedures. The compiler picks the right one at compile time based on the argument types, kinds and ranks. This is how intrinsics like abs work for integers, reals and complex numbers.

fortran · try it yourself
module swapping
  implicit none
  private
  public :: swap

  interface swap                      ! the generic name
    module procedure swap_int, swap_real, swap_string
  end interface swap

contains

  subroutine swap_int(a, b)
    integer, intent(inout) :: a, b
    integer :: t
    t = a; a = b; b = t
  end subroutine swap_int

  subroutine swap_real(a, b)
    real, intent(inout) :: a, b
    real :: t
    t = a; a = b; b = t
  end subroutine swap_real

  subroutine swap_string(a, b)
    character(len=*), intent(inout) :: a, b
    character(len=len(a)) :: t
    t = a; a = b; b = t
  end subroutine swap_string

end module swapping

program generic_demo
  use swapping
  implicit none
  integer :: i = 1, j = 2
  real :: x = 1.5, y = -2.5
  character(len=5) :: s = 'left', t = 'right'

  call swap(i, j)
  call swap(x, y)
  call swap(s, t)
  print '(2i3)', i, j
  print '(2f6.2)', x, y
  print '(a, 1x, a)', s, t
end program generic_demo
  2  1
 -2.50  1.50
right left 

Users of the module only see swap; the specific names are private details. If you call swap with arguments that match no specific procedure (say, an integer and a real), you get a compile error.

Generics over kinds and ranks

A common use is to provide the same operation for single and double precision, or for scalars and arrays:

fortran · try it yourself
module stats
  use iso_fortran_env, only: real32, real64
  implicit none
  private
  public :: mean

  interface mean
    module procedure mean_r32, mean_r64, mean_matrix
  end interface mean

contains

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

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

  function mean_matrix(x) result(m)           ! rank 2: mean of each column
    real(real64), intent(in) :: x(:, :)
    real(real64) :: m(size(x, 2))
    m = sum(x, dim=1) / size(x, 1)
  end function mean_matrix

end module stats

program use_stats
  use iso_fortran_env, only: real32, real64
  use stats
  implicit none
  real(real64) :: table(2, 3) = reshape([1, 3, 10, 20, 5, 6], [2, 3])

  print '(f10.6)', mean([1.0_real32, 2.0_real32, 4.0_real32])
  print '(f18.15)', mean([1.0_real64, 2.0_real64, 4.0_real64])
  print '(3f8.2)', mean(table)
end program use_stats
  2.333333
 2.333333333333333
    2.00   15.00    5.50

Note: Two specific procedures in a generic must be distinguishable by their arguments. Differences only in argument names or in the result type are not enough.

Procedure arguments: abstract interfaces

Procedures can be passed as arguments to other procedures, for example the function to integrate or the equation to solve. An abstract interface describes the required signature, and procedure(name) declares a dummy argument with that signature:

fortran · try it yourself
module calculus
  use iso_fortran_env, only: real64
  implicit none
  integer, parameter :: dp = real64

  abstract interface
    function real_func(x) result(y)
      import :: dp                 ! make dp visible inside the interface
      real(dp), intent(in) :: x
      real(dp) :: y
    end function real_func
  end interface

contains

  function derivative(f, x) result(d)
    procedure(real_func) :: f
    real(dp), intent(in) :: x
    real(dp) :: d
    real(dp), parameter :: h = 1.0e-5_dp
    d = (f(x + h) - f(x - h)) / (2 * h)     ! central difference
  end function derivative

  function cube(x) result(y)
    real(dp), intent(in) :: x
    real(dp) :: y
    y = x**3
  end function cube

  function wave(x) result(y)
    real(dp), intent(in) :: x
    real(dp) :: y
    y = sin(x)
  end function wave

end module calculus

program use_calculus
  use calculus
  implicit none
  print '(a, f10.6)', "cube'(2) ~ ", derivative(cube, 2.0_dp)
  print '(a, f10.6)', "sin'(0)  ~ ", derivative(wave, 0.0_dp)
end program use_calculus
cube'(2) ~  12.000000
sin'(0)  ~   1.000000

Inside an interface block, names from the enclosing module are not visible unless you import them, which is why import :: dp is needed.

Procedure pointers

A procedure pointer can be pointed at different procedures with matching interfaces at run time, like a function pointer in C:

fortran
procedure(real_func), pointer :: f => null()
f => cube
print *, f(3.0_dp)      ! 27
f => wave

Test yourself

What does a generic interface do?

  1. Hides a procedure
  2. Gives one name to several specific procedures, chosen by argument types at compile time
  3. Makes procedures run in parallel
  4. Creates a template that is instantiated at run time

Why is import :: dp needed inside an abstract interface in a module?

  1. Interface bodies don't see the host's names unless they are imported
  2. To import a module from disk
  3. It makes dp public
  4. It is optional decoration

Which pair of specific procedures can NOT be combined in one generic?

  1. One taking integer, one taking real
  2. One taking a scalar, one taking a 1-D array
  3. Two taking real that differ only in their result type
  4. One taking real32, one taking real64