Fortran/language extensions

< Fortran

Procedure Overloading

Like several other languages, Fortran 90 and newer supports the ability to select the appropriate routine from a list of routines based on the arguments passed. This selection is done at compile time and is thus unencumbered by run-time performance penalties. This feature is accessed by use of modules and the interface block.

In the following example, a module is specified with contains a single logical function which can handle arguments of various types.

module extension_mod
   implicit none
   private

   interface f
      module procedure f_i
      module procedure f_r
      module procedure f_z
   end interface

   public::f

contains

   function f_i(x) result(y)
      integer,intent(in)::x
      integer::y

      y = x**2-1
   end function f_i

   function f_r(x) result(y)
      real,intent(in)::x
      real::y

      y = x**2-1.0
   end function f_r

   function f_z(x) result(y)
      complex,intent(in)::x
      complex::y

      y = x**2-1.0
   end function f_z

end module extension_mod

A program which uses this module now has access to a single logical function f which accepts arguments which are of the integer, real, or complex data types. The return type of the function is the same as the input type. In this way the routine is much like many of the intrinsic functions defined as part of the Fortran standard. An example program is given below:

program main
   use extension_mod
   implicit none

   integer::xi,yi
   real::xr,yr
   complex::xz,yz

   xi = 2
   xr = 2.0
   xz = 2.0

   yi = f(xi)
   yr = f(xr)
   yz = f(xz)

end program main

Derived Data Types

Fortran 90 and newer supports the creation of new data types which are composites of existing types. In some ways this is similar to an array, but the components need not be all of the same type and they are referenced by name, not index. Such data types must be declared before variables of that type, and the declaration must be in scope to be used. An example of a simple 2d vector type is given below.

type::vec_t
   real::x,y
end type

Variables of this type can be declared much like any other variable, including variable characteristics such are pointer or dimension.

type(vec_t)::a,b
type(vec_t),dimension(10)::vecs

Using derived data types, the Fortran language can be extended to represent more diverse types of data than those represented by the primitive types.

Operator Overloading

Operators can be overloaded so that derived data types support the standard operations, opening the possibility of extending the Fortran language to have new types which behave nearly like the native types.

This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.