Fortran/structures
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 | edit source]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
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 | edit source]!> show the usage of type-bound procedures (pass/nopass arguments)
module test_m
implicit none
private
public test_type
type test_type
integer :: i
contains
procedure, nopass :: print_hello
procedure :: print_int
end type
contains
!> do not process type specific data => nopass
subroutine print_hello
print *, "hello"
end subroutine
!> process type specific data => first argument is "this" of type "class(test_type)"
!! use class and not type below !!!!
subroutine print_int(this)
class(test_type), intent(in) :: this
print *, "i", this%i
end subroutine
end module
program main
use test_m
implicit none
type (test_type) :: obj
obj%i = 1
call obj%print_hello
call obj%print_int
end program
Example: parameterized type
[edit | edit source]! 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
type (matrix(rows=3, cols=3)) :: my_obj
end program
References
[edit | edit source]- ↑ A Look at Fortran 90 - Lahey computer systems