次のFortran標準(2015)は、select case
に似たselect rank
構造を持っています。私の例では、仮定ランクのダミー変数のrank
組み込みのselect case
構成を使用しています。
module my_type
use, intrinsic :: iso_fortran_env, &
ip => INT32, &
wp => REAL64
implicit none
private
public :: MyType
type MyType
real (wp) :: rank0
real (wp), allocatable :: rank1(:)
real (wp), allocatable :: rank2(:,:)
real (wp), allocatable :: rank3(:,:,:)
contains
procedure :: create => create_my_type
procedure :: destroy => destroy_my_type
end type MyType
contains
subroutine create_my_type(this, array)
! calling arguments
class (MyType), intent (in out) :: this
real (wp), intent (in) :: array(..) !! Assumed-rank dummy variable
! local variables
integer (ip), allocatable :: r(:)
select case(rank(array))
case (0)
return
case (1)
r = shape(array)
allocate(this%rank1(r(1)))
case (2)
r = shape(array)
allocate(this%rank2(r(1), r(2)))
case (3)
r = shape(array)
allocate(this%rank3(r(1), r(2), r(3)))
case default
error stop 'array must have rank 0,1,2, or 3'
end select
! Release memory
if (allocated(r)) deallocate(r)
end subroutine create_my_type
subroutine destroy_my_type(this)
! calling arguments
class (MyType), intent (in out) :: this
if (allocated(this%rank1)) deallocate(this%rank1)
if (allocated(this%rank2)) deallocate(this%rank2)
if (allocated(this%rank3)) deallocate(this%rank3)
end subroutine destroy_my_type
end module my_type
program main
use, intrinsic :: iso_fortran_env, only: &
ip => INT32, &
wp => REAL64
use my_type, only: &
MyType
implicit none
type (MyType) :: foo
real (wp) :: a0, a1(42), a2(42,42), a3(42,42,42)
print *, rank(a0)
print *, rank(a1)
print *, rank(a2)
print *, rank(a3)
! Allocate array of rank 3
call foo%create(a3)
print *, rank(foo%rank3)
print *, shape(foo%rank3)
print *, size(foo%rank3)
! Release memory
call foo%destroy()
end program main
あなたが知っているように、実行時に配列のランクを割り当てることはできません。あなたはこれを回避するために起こりうる不具合の一つを示すスニペットを私たちに示しました。慎重に 'include 'を使うなど、他にもある。派生型の中にrank-1配列をラップして、それがrank-n(実行時にnを選択する)のように操作を書くことさえできます。しかし、なぜあなたがこれを望んでいるのかを私たちに教えれば、施設なしでプログラムを書く方法を教えてくれるかもしれません。 –
ご返信ありがとうございます。私がこれをしたいのは、可能ならば、私のコードは(すべてのif文なしで)もっときれいに見えて、変更しやすいと思うからです。しかし、おそらく、私がやっていることには大惨事です。私のプログラムでは、1d時間依存型シュレディンガー方程式(TDSE)、2D TDSEを解くことができ、配列Aは波動関数の次元になります。派生型で提案したソリューションへの参照はありますか? – Lun