如何声明在Fortran中返回数组的函数的类型? [英] How to declare the type of a function that returns an array in Fortran?
问题描述
我有一个返回数组的函数,比如说
I have function that returns an array, say
function f(A)
implicit none
real, intent(in) :: A(5)
real, intent(out) :: f(5)
f = A+1
end
我的问题是,如何在主程序单元中定义 f
?例如
My question is, how can I define f
in the main program unit? E.g.
program main
implicit none
real :: A(5)
real, dimension(5), external :: f ! does not work
...
end
推荐答案
您需要一个显式接口.您可以通过几种方式来做到这一点.
You need an explicit interface. You can do this in a few ways.
-
明确地在调用
f
的作用域内:
interface
function f(A)
implicit none
real, intent(in) :: A(5)
real :: f(5)
end function
end interface
将该函数作为内部函数放置在程序宿主作用域中
Place the function in your program host scope as an internal function:
program main
...
contains
function f(A)
implicit none
real, intent(in) :: A(5)
real :: f(5)
f = A+1
end
end program
将功能放置在模块中
Place the function in a module:
module A
contains
function f(A)
implicit none
real, intent(in) :: A(5)
real :: f(5)
f = A+1
end
end module
program main
use A
...
end program
使用具有不同自变量的不同过程的显式接口,并返回类型,种类和等级.
Use the explicit interface from a different procedure with the same arguments and return type, kind and rank.
program main
interface
function r5i_r5o(r5)
implicit none
real, intent(in) :: r5(5)
real :: r5i_r5o(5)
end function
end interface
procedure(r5i_r5o) :: f
...
end program
function f(A)
implicit none
real, intent(in) :: A(5)
real :: f(5)
f = A+1
end
最干净的方法是使用模块的选项3.这为您提供了一个自动显式接口的好处(无需在调用 f
的任何地方都执行选项#1),并使您的函数在使用该模块的任何地方都可用,而不是像下面那样局限于特定的作用域单元.选项#2.如果您有许多具有相同参数和返回类型的过程,那么选项#4可能会很方便,因为可以将一个显式接口重新用于所有这些过程.
The cleanest way of doing this is option #3 using modules. This gives you the benefit of an automatic explicit interface (not needing to do option #1 everywhere you call f
) and makes your function available everywhere the module is used rather than limited to a specific scoping unit as in option #2. Option #4 can be handy if you have many procedures with the same argument and return types since one explicit interface can be re-used for all of them.
这篇关于如何声明在Fortran中返回数组的函数的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!