Derived types and structure constructors

A derived type is Fortran's record: a named group of components that travel together. The type is declared once, usually in a module, and every variable of it holds all the components at once. This lesson defines a point, builds values with the structure constructor, reads and writes the components with %, nests one type inside another, and passes a whole value into a procedure and back out of it.

Defining a type

type :: point starts the definition and end type point ends it. Between them are the components, each declared the way a variable is. The type itself is a template and holds no data; a variable of the type, a type(point) :: a, is the thing with values in it.

The type lives in a module because a type used by two program units has to be the same type in both, and the module is what makes it one. A type declared separately in two programs is two types that happen to look alike, and the compiler will not accept a value of one where the other is expected.

The file dt.f90:

module geom implicit none type :: point real :: x = 0.0 real :: y = 0.0 end type point contains function midpoint(a, b) result(m) type(point), intent(in) :: a, b type(point) :: m m%x = (a%x + b%x) / 2.0 m%y = (a%y + b%y) / 2.0 end function midpoint function distance(a, b) result(d) type(point), intent(in) :: a, b real :: d d = sqrt((a%x - b%x)**2 + (a%y - b%y)**2) end function distance subroutine show(p, label) type(point), intent(in) :: p character(len=*), intent(in) :: label print '(a,a,f6.1,a,f6.1,a)', label, ' (', p%x, ', ', p%y, ')' end subroutine show end module geom program dtdemo use geom implicit none type(point) :: a, b, m type(point) :: pts(3) integer :: i a = point(1.0, 2.0) b = point(x=5.0, y=6.0) call show(a, 'a =') call show(b, 'b =') m = midpoint(a, b) call show(m, 'mid =') print '(a,f8.3)', 'distance(a, b) = ', distance(a, b) pts = [point(0.0, 0.0), point(3.0, 0.0), point(3.0, 4.0)] do i = 1, size(pts) print '(a,i0,a,f6.1,a,f6.1,a)', 'pt(', i, ') = (', pts(i)%x, ', ', pts(i)%y, ')' end do end program dtdemo

gfortran -Wall -Wextra -std=f2018 dt.f90 -o dt
./dt

a = ( 1.0, 2.0)
b = ( 5.0, 6.0)
mid = ( 3.0, 4.0)
distance(a, b) = 5.657
pt(1) = ( 0.0, 0.0)
pt(2) = ( 3.0, 0.0)
pt(3) = ( 3.0, 4.0)

The distance between (1, 2) and (5, 6) is sqrt(16 + 16) = 5.657, which is the number printed: a derived type is a way to name a value, and the arithmetic inside it is the arithmetic of its components.

The structure constructor

point(1.0, 2.0) is the structure constructor of the type: the type name followed by one value per component, in the order the components were declared. It builds a value, so it appears on the right of an assignment, inside an array constructor, or as an argument; it is not a declaration and it does not name a variable.

point(x=5.0, y=6.0) is the same value with the components named. The keyword form does not depend on the order, which matters when a type has six components of the same type and a reader cannot tell from the position which is which. A component with a default initialiser may be left out of either form; a component without one may not.

Nested components and defaults

A component may itself be a derived type, and then % is read twice: s%a%x is the x of the point at the start of the segment. A component may also carry a default initialiser, which is how a character component gets a value when the constructor does not supply one.

The file nest.f90:

module geom implicit none type :: point real :: x = 0.0 real :: y = 0.0 end type point type :: segment type(point) :: a, b character(len=12) :: name = 'unnamed' end type segment contains function length(s) result(d) type(segment), intent(in) :: s real :: d d = sqrt((s%b%x - s%a%x)**2 + (s%b%y - s%a%y)**2) end function length end module geom program nestdemo use geom implicit none type(segment) :: s, t s = segment(point(0.0, 0.0), point(3.0, 4.0), 'hypotenuse') t = segment(a=point(1.0, 1.0), b=point(4.0, 5.0)) print '(a,a,f8.3)', trim(s%name), ': length = ', length(s) print '(a,f8.3)', 't: length = ', length(t) print '(a,a)', 't name = ', trim(t%name) print '(a,f6.1,a,f6.1,a)', 't starts at (', t%a%x, ', ', t%a%y, ')' end program nestdemo

gfortran -Wall -Wextra -std=f2018 nest.f90 -o nest
./nest

hypotenuse: length = 5.000
t: length = 5.000
t name = unnamed
t starts at ( 1.0, 1.0)

t was built without a name and got 'unnamed' from the default, and its start point was named rather than counted, so the two keyword arguments could be written in either order. Both segments are five units long, one along the diagonal of a 3-4-5 triangle and one along (3, 4).

A type as an argument and a result

midpoint takes two points with intent(in) and returns a point: a derived type is a value like a real, so a function can return one and a subroutine can take one. The dummy argument declaration type(point), intent(in) :: a is checked by the compiler against the actual argument, which is another thing a module buys: a caller that passes a type(segment) is refused before the program runs.

Assignment between two variables of the same type copies every component. That is the rule that makes a type feel like a value: m = midpoint(a, b) puts a copy of the result into m, and changing m afterwards does not touch the result. Section 079 looks at what the rule means when a component is an allocatable array.

An array of a type

type(point) :: pts(3) is an array of three points, and the array constructor of the first program fills it with three type constructors. Whole-array assignment works component by component, and a loop over the elements is an ordinary loop over an array. Nothing else about arrays changes: a section pts(2:3) is a section of points, and size(pts) is three.

Assigning the wrong thing

A type and its components are different types, and the compiler will not convert one into the other:

module geom implicit none type :: point real :: x = 0.0 real :: y = 0.0 end type point end module geom program badassign use geom implicit none type(point) :: p p = 5.0 print *, p%x end program badassign

gfortran -Wall -Wextra -std=f2018 e1.f90 -o e1

e1.f90:14:6:

14 | p = 5.0
| 1
Error: Cannot convert REAL(4) to TYPE(point) at (1)

The compiler prints the type as TYPE(point) and the real as REAL(4): the kind is part of the type name in every message. The fix is a constructor, p = point(5.0, 0.0), and the message is telling a reader exactly that.

What a type is not

A derived type is not a class and has no methods until lesson 073 gives it type-bound procedures. It has no comparison: p == q is rejected, and the message says the operands are derived types, because the language has no rule for comparing two records. It has no arithmetic until an operator is defined for it, which is the mechanism of lesson 067.

A type is also not a pointer: a = b copies, it does not alias. In a language where objects are references by default that takes a while to get used to, and it is the source of the deep-copy questions in section 079. For a value of a few components the copy is what a reader expects; for a value with a million-element array inside it is a cost worth knowing about.

Exercises

  1. Give point a third component integer :: id = 0 and rebuild. Which constructors in the program still compile, and which do not?
  2. Write a function translate(p, dx, dy) that returns a new point moved by dx and dy. Does it need intent(inout)?
  3. Add a type(triangle) with three points and a function that returns its perimeter. Which components does the constructor take, in which order?
  4. Try print *, a == b with two points and read the error. What would you have to write for the comparison to work?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does type :: point declare?

    Answer

    A derived type with the components listed until END TYPE

    The definition is a template; variables are declared with type(point).

  2. What is point(1.0, 2.0)?

    Answer

    The structure constructor: a value with one component per argument

    It builds a value of the type in component order.

  3. What does s%a%x read?

    Answer

    The x component of the point named a inside s

    Each % steps into one level of the record.

  4. What does this program print? module m implicit none type :: pair integer :: a = 1 integer :: b = 2 end type pair end module m program p use m implicit none type(pair) :: v v = pair(b=10) print *, v%a, v%b end program p

    Answer

    1 10

    a keeps its default and b is the named argument.

  5. What happens on m = midpoint(a, b) when both are points?

    Answer

    Every component of the result is copied into m

    Assignment of a derived type copies all components.

  6. Where does a derived type belong?

    Answer

    In a module, so every user gets the same type

    Two separate declarations are two different types.

  7. Which component may be left out of a constructor?

    Answer

    One with a default initialiser

    The default fills the gap; a component without one must be given.

  8. What does gfortran report for p = 5.0 when p is a point?

    Answer

    Error: Cannot convert REAL(4) to TYPE(point)

    A real and a record are different types with no conversion.

  9. What does p == q do for two values of a type with no defined operator?

    Answer

    It is a compile error; the language has no comparison for records

    Comparison needs a definition, as in lesson 067.

  10. What is a type(point) :: pts(3)?

    Answer

    An array of three points, one value per element

    The type is the element type of the array.

The programs on this page were built with GNU Fortran (Alpine 15.2.0) 15.2.0 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev