Fortran Derived Types
A derived type groups related values into one new type, like a struct in C or a simple class in Python. A particle has a position, a velocity and a mass; a date has a year, month and day. Bundling them makes code easier to read and procedures easier to call.
Defining a type
module shapes
implicit none
type :: point
real :: x
real :: y
end type point
end module shapes
program use_point
use shapes
implicit none
type(point) :: a, b
real :: d
a%x = 1.0 ! components are accessed with %
a%y = 2.0
b = point(4.0, 6.0) ! structure constructor
d = sqrt((b%x - a%x)**2 + (b%y - a%y)**2)
print '(a, 2f6.2)', 'a = ', a%x, a%y
print '(a, 2f6.2)', 'b = ', b%x, b%y
print '(a, f6.2)', 'distance = ', d
end program use_pointa = 1.00 2.00
b = 4.00 6.00
distance = 5.00
type :: name … end type namedefines the type, usually in a module so many units can use it.type(point) :: adeclares a variable of the type.a%xaccesses a component. (Fortran uses%where many languages use..)point(4.0, 6.0)is the structure constructor: one value per component, in order, or by keyword:point(y=6.0, x=4.0).
Default values and mixed components
Components can be of any type, including arrays, strings, allocatable arrays and other derived types. They can also have default values, which makes those arguments optional in the constructor:
module inventory
implicit none
type :: item
character(len=20) :: name
integer :: quantity = 0
real :: unit_price = 0.0
end type item
end module inventory
program shop
use inventory
implicit none
type(item) :: stock(3)
integer :: i
real :: total
stock(1) = item('notebook', 25, 2.40)
stock(2) = item('pen', quantity=120, unit_price=0.85)
stock(3) = item('stapler') ! defaults for the rest
total = 0.0
do i = 1, size(stock)
print '(a20, i5, f8.2)', stock(i)%name, stock(i)%quantity, stock(i)%unit_price
total = total + stock(i)%quantity * stock(i)%unit_price
end do
print '(a, f8.2)', 'stock value: ', total
print '(a, i0)', 'total units: ', sum(stock%quantity) ! component of an array
end program shopnotebook 25 2.40
pen 120 0.85
stapler 0 0.00
stock value: 162.00
total units: 145
stock%quantity is an integer array made of the quantity component of every element, so array intrinsics like sum work on it directly.
Types as procedure arguments
Passing one structure instead of many loose values keeps argument lists short:
module bodies
use iso_fortran_env, only: real64
implicit none
integer, parameter :: dp = real64
type :: body
character(len=10) :: name
real(dp) :: mass ! kg
real(dp) :: pos(3) ! m
real(dp) :: vel(3) ! m/s
end type body
contains
function kinetic_energy(b) result(e)
type(body), intent(in) :: b
real(dp) :: e
e = 0.5_dp * b%mass * sum(b%vel**2)
end function kinetic_energy
subroutine advance(b, dt)
type(body), intent(inout) :: b
real(dp), intent(in) :: dt
b%pos = b%pos + b%vel * dt
end subroutine advance
end module bodies
program simulate
use bodies
implicit none
type(body) :: probe
integer :: step
probe = body('probe', 500.0_dp, [0.0_dp, 0.0_dp, 0.0_dp], [3.0_dp, 4.0_dp, 0.0_dp])
print '(a, f10.1, a)', 'kinetic energy: ', kinetic_energy(probe), ' J'
do step = 1, 3
call advance(probe, 10.0_dp)
print '(a, i0, a, 3f8.1)', 'after step ', step, ': ', probe%pos
end do
end program simulatekinetic energy: 6250.0 J
after step 1: 30.0 40.0 0.0
after step 2: 60.0 80.0 0.0
after step 3: 90.0 120.0 0.0
Nested types and allocatable components
module school
implicit none
type :: student
character(len=:), allocatable :: name
integer, allocatable :: marks(:)
end type student
type :: course
character(len=:), allocatable :: title
type(student), allocatable :: roster(:)
end type course
end module school
program classes
use school
implicit none
type(course) :: physics
integer :: i
physics%title = 'Physics 101'
physics%roster = [student('Amara', [78, 85, 91]), &
student('Bo', [64, 70]), &
student('Chen', [88, 92, 95, 99])]
print '(a)', physics%title
do i = 1, size(physics%roster)
associate (s => physics%roster(i))
print '(2x, a, a, i0, a, f5.1)', s%name, ': ', size(s%marks), &
' marks, average ', real(sum(s%marks)) / size(s%marks)
end associate
end do
end program classesPhysics 101
Amara: 3 marks, average 84.7
Bo: 2 marks, average 67.0
Chen: 4 marks, average 93.5
Each student has a name and a mark list of its own length, thanks to deferred-length and allocatable components. Copying a structure (b = a) copies its allocatable components too, so the copy is fully independent.
The associate construct gives a short alias (s) to a long expression for the duration of a block, which keeps deeply nested component access readable.
Printing a whole structure
A structure can be printed directly with list-directed or formatted output. Its components are printed in order, as if they were listed one by one (this doesn't work for types with allocatable or pointer components, which need a custom routine):
module dates
implicit none
type :: date
integer :: year, month, day
end type date
end module dates
program print_type
use dates
implicit none
type(date) :: launch = date(1969, 7, 16)
print '(i4.4, "-", i2.2, "-", i2.2)', launch
end program print_type1969-07-16
Test yourself
How do you access component mass of a variable p of a derived type?
p.massp->massp%massp[mass]
Given type(item) :: s(10), what is s%quantity?
- The quantity of s(1)
- An array of the 10 quantity components
- A compile error
- The number of components
What does associate (v => body%vel) do?
- Copies the velocity
- Creates a temporary alias
vfor the expression within the block - Allocates a pointer
- Renames the component permanently