Derived Data Types

A fairly recent feature in FORTRAN is the opportunity to invent our own composite types of data. Instead of having a variable of one specific elementary type, we can invent and name a type which has several components each of an elementary type. This is sometimes called a "structure" or a "record".

Example: Suppose we want to have variables representing points on the X-Y plane.

         Type Point
           Real :: X
           Real :: Y
         End Type Point

We can now have variable of type Point:

         Point :: P, Q

and we can initialize them using constants of type Point:

         Point :: R = Point(1.5, 3.9)

or we can assign values similarly:

         Q = Point(-5.4, 0.3)

or we can have constants of type Point:

         Point, Parameter :: Center = Point(0.0, 0.0)

Here the expression on the right-hand side is a "constructor" for Point; it "constructs" a value of type Point. Its arguments could be constants or expressions of the proper type.

If we want to refer to the components of a Point variable, we can:

         Print *, R%X

or

         R%X = 8.9

where we need

         R, the name of the variable
         % , to indicate we want a component (the "component selector")
         X, the name of the component

We could have more complicated types:

         Type Person
           Character(15) :: LastName
           Character(10) :: FirstName
           Integer :: Age
           Character :: Sex
         End Type Person

         Person :: Client = Person('Jones', 'John', 25, 'M')

Likewise, we might have a user-defined type to hold a date (year, month and day) or a user's name and password.

We could have arrays of a user-defined type, and we could sort them using one of the components as the key. If we did not have a user-defined type, we would need a number of parallel arrays, one per component.

To do input or output using a user-defined type, we have to work with one component at a time.