是否可以在 Fortran 中编写具有动态输入的函数?

Is it possible to write a function with dynamic input in Fortran?

我是 fortran 的新手,想知道是否可以编写带有动态输入的函数或子例程?例如,如果我想要 function/subroutine :

function/subroutine a (inputs)

  integer, dimension(:), allocatable :: b
  integer :: i,j

  i = number of inputs
  allocate(b(i))

  do j=1,i
    b(i)=input(i)
  end do

end function a

所以我每次调用 function/subroutine 时输入的数量可能不同。可能吗?

当所有的参数都是同一类型时,可以用数组传递:

subroutine a(inputs)
    integer :: inputs(:)
    integer,  allocatable :: b(:)
    integer :: i,j

    i = size(inputs)
    allocate(b(i))

    do j=1,i
      b(i)=input(i)
    end do

如果它们属于不同类型,您可以使用可选的虚拟参数。您必须在访问每个参数之前检查它是否存在。

subroutine a(in1, in2, in3)
    integer :: in1
    real :: in2
    character :: in3

    if (present(in1)) process in1
    if (present(in2)) process in2
    if (present(in3)) process in3

您还可以使用泛型,您可以在其中手动指定所有可能的组合,然后编译器选择正确的特定过程进行调用。查看您最喜欢的教科书或教程了解更多

module m

  interface a
    module procedure a1
    module procedure a1
    module procedure a1
  end interface

contains

   subroutine a1(in1)
     do something with in1
   end subroutine

   subroutine a2(in1, in2)
     do something with in1 and in2
   end subroutine

   subroutine a2(in1, in2, in3)
     do something with in1, in2 and i3
   end subroutine

end module

...
use m
call a(x, y)