From Wikibooks, open books for an open world
Jump to navigation Jump to search

Structures, structured types, or derived types(DT) were first introduced in Fortran 90.[1] Structures allow the user to create data types that hold multiple different variables.

Derived types are often implemented within modules such that one can easily reuse them. They might also hold type-bound procedures which are intended to process the structure. The arguments pass(name), nopass indicate whether the object should be passed as the first argument.

Similar to the character data type, structures can be parameterized by two different parameter types: kind, len. The kind parameters must be known at compile type (consist of constants) whereas the len parameters can change at runtime.

Simple example[edit]

As an example, we can define a new structure type, 'Fruit' which stores some basic fruit variables:

type fruit
  real diameter      ! in mm
  real length        ! in mm
  character colour
end type fruit

We can declare two 'fruit' variables, and assign them values:

type(fruit) apple, banana
apple = fruit(50,45,"red")
banana%diameter = 40
banana%length = 200
banana%colour= "yellow"

And we can then use the fruit variables and their child values in normal Fortran operations.

Example: Type-bound procedures[edit]

!> show the usge of type-bound procedures (pass/nopass arguments)
module test_mod

  implicit none

  type, public :: test_type
    integer :: i
    procedure, nopass :: print_hello
    procedure, pass(this) :: print_int
  end type test_type

  !> do not process type specific data => nopass
  subroutine print_hello
    implicit none
    print *, "hello"
  end subroutine print_hello

  !> process type specific data => pass
  !! use class and not type below !!!!
  subroutine print_int( this )
    implicit none
    class(test_type) , intent(in) :: this
    print *, "i:", this%i
  end subroutine print_int

end module

program main

  use test_mod
  implicit none

  type(test_type) :: my_obj
  my_obj%i = 1

  call my_obj%print_hello
  call my_obj%print_int

end program main

Example: Parameterized type[edit]

! testing types with params: kind + len
program main

  implicit none

  type matrix( rows, cols, k)
    integer, len :: rows, cols
    integer, kind :: k = kind(0.0)    ! optional/default value
    real( kind=k ), dimension(rows, cols) :: vals
  end type matrix

  type(matrix(rows=3, cols=3)) :: my_obj

end program main


  1. A Look at Fortran 90 - Lahey computer systems