【问题标题】:Function as an output argument作为输出参数的函数
【发布时间】:2013-11-09 15:37:32
【问题描述】:

我想创建一个返回函数作为输出的子例程。我怎样才能做到这一点?我将举一个我认为应该如何的例子(我知道它写得不好)

module fun_out

contains

subroutine exponential(F,a)
     interface, intent(out)

        function f(x)
         real, intent(in)::x
         real :: f(2)
        end function
     end interface
     real,intent(in):: a

   F=exp(a*x)

end subroutine exponential

end module

有了这个,我应该从输出中的指数族中获取一个函数。

【问题讨论】:

    标签: function fortran output


    【解决方案1】:

    你必须返回一个函数指针。这可以在 Fortran 2003 中完成。

       procedure(name_of_interface), pointer :: f
    

    但是你不能期望完全的词法作用域闭包,只是纯指针。

    您必须将程序准备为普通的外部、模块或 F2008 甚至内部程序(有一些限制)并指向它:

        f => my_function
    

    在您的情况下,您有参数a,并且您似乎想使用它作为捕获的闭包变量。在 Fortran 中是不可能的。您要么必须每次都将它传递给函数,要么使用 Functor 模式(派生类型保存捕获的参数),或者使用内部过程(但这仅在其宿主过程中有效)。

    【讨论】:

      【解决方案2】:

      您基本上可以通过定义函子对象来做到这一点(正如Vladimir's answer 中提到的)。它们有一个特定的函数返回值(例如getvalue()),并且根据它们的初始化,它们可能会返回自定义的函数值。

      下面的示例详细说明了这一点。通用函子在functor_module 中定义,在expfunc_module 中导出了指数函数族的具体实现。然后,在主程序中,您可以在指数中使用不同的前置因子初始化不同的实例,并可以使用它们的getvalue() 方法来获取适当的函数值。:

      module functor_module
        implicit none
      
        integer, parameter :: wp = kind(1.0d0)
      
        type, abstract :: functor
        contains
          procedure(getvalue_iface), deferred :: getvalue
        end type functor
      
        interface 
          function getvalue_iface(self, xx) result(yy)
            import
            class(functor), intent(in) :: self
            real(wp), intent(in) :: xx
            real(wp) :: yy
          end function getvalue_iface
        end interface
      
      end module functor_module
      
      
      module expfunc_module
        use functor_module
        implicit none
      
        type, extends(functor) :: expfunc
          real(wp) :: aa
        contains
          procedure :: getvalue
        end type expfunc
      
      contains
      
        function getvalue(self, xx) result(yy)
          class(expfunc), intent(in) :: self
          real(wp), intent(in) :: xx
          real(wp) :: yy
      
          yy = exp(self%aa * xx)
      
        end function getvalue
      
      end module expfunc_module
      
      
      program test_functors
        use expfunc_module
        implicit none
      
        type(expfunc) :: func1, func2
        real(wp) :: xx
      
        func1 = expfunc(1.0_wp)
        func2 = expfunc(2.0_wp)
        xx = 1.0_wp
        print *, func1%getvalue(xx)   ! gives exp(1.0 * xx) = 2.718...
        print *, func2%getvalue(xx)   ! gives exp(2.0 * xx) = 7.389...
      
      end program test_functors
      

      【讨论】:

        猜你喜欢
        • 2021-10-23
        • 1970-01-01
        • 1970-01-01
        • 2022-06-29
        • 1970-01-01
        • 1970-01-01
        • 2013-11-30
        • 2019-09-04
        • 1970-01-01
        相关资源
        最近更新 更多