next up previous contents
Next: Pointers and Dynamic Data Up: Survey of the New Previous: Modules

Derived Types and Generic Functions

 

Derived or user-defined types, similar to records or structures in other languages, are available in Fortran 90. Derived types are built from the intrinsic types or other derived types and allow the creation of data types that behave as if they were intrinsic types. Generic functions, another new feature in Fortran 90, help to make the support for derived data types complete. A generic function such as `+' may be extended to operate directly on a derived type, combining the notational convenience and clarity of operators with the abstraction of derived types. The module and program below illustrate the extension of the generic operator ` +', to operate on a derived type, interval.

module IntervalArithmetic
   type interval
      real a  ! Left endpoint
      real b  ! Right endpoint
   end type interval

   interface operator (+)
      module procedure addIntervals
   end interface

   contains

   function addIntervals( first, second )
      type( interval ) addIntervals
      type( interval ), intent( in ) :: first, second

      ! Numerically, the left and right endpoints of the interval
      !  sum should be rounded down and up, respectively, to 
      !  ensure that numbers in the two intervals are also in the 
      !  sum.  This has been omitted to simplify the example.

      addIntervals = interval( first%a + second%a, &
                               first%b + second%b )
   end function addIntervals
end module IntervalArithmetic

program Intervals
   use IntervalArithmetic

   type( interval ) :: x = interval( 1.0, 2.0 )
   type( interval ) :: y = interval( 3.0, 4.0 )
   type( interval ) z

   z = x + y
   print *, 'Interval sum: (', z%a, ',', z%b, ').'
end program Intervals



next up previous contents
Next: Pointers and Dynamic Data Up: Survey of the New Previous: Modules