Fortran/構造化データ

出典: フリー教科書『ウィキブックス(Wikibooks)』
Wikipedia
Wikipedia
ウィキペディアFortranの記事があります。


構造体構造化型、または派生型(DT)は、最初にFortran 90で導入されました。[1] 構造体は、複数の異なる変数を保持するデータ型を作成できるようにします。 派生型は、一般にモジュール内で実装され、簡単に再利用できるようになっています。また、構造体を処理するための型に関連付けられた手続きを保持することができます。引数pass(name), nopassは、オブジェクトを最初の引数として渡すかどうかを示します。 文字列のデータ型characterと同様に、構造体は2つの異なるパラメータ型でパラメータ化できます:kind, lenkindパラメータはコンパイル時に既知でなければならず(定数で構成されています)、lenパラメータは実行時に変更できます。

簡単な例[編集]

例として、新しい構造体タイプ 'Fruit' を定義し、いくつかの基本的な果物変数を保持します:

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

2つの 'fruit' 変数を宣言し、値を割り当てることができます:

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

その後、通常のFortran操作で果物変数とその子の値を使用できます。

例: 型に関連付けられた手続き[編集]

!> 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
    !> タイプ固有データを処理しない => nopass
    subroutine print_hello
        print *, "hello"
    end subroutine

    !> タイプ固有データを処理する => 最初の引数は型 "class(test_type)" の "this"
    !! classを使用し、typeではなく !!!!
    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

例: パラメータ付き型[編集]

! パラメータを持つ型のテスト: 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

脚註[編集]

  1. ^ A Look at Fortran 90 - Lahey computer systems