如何声明在 Fortran 中返回数组的函数的类型? [英] How to declare the type of a function that returns an array in Fortran?

查看:24
本文介绍了如何声明在 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.

  1. 在调用 f 的作用域单元中显式:

  1. Explicitly in the scoping unit that calls 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屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆