作为输出参数的函数

时间:2013-10-30 07:06:37

标签: function fortran output

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

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

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

2 个答案:

答案 0 :(得分:3)

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

   procedure(name_of_interface), pointer :: f

但是,你必须不要指望完整的词法范围闭包,只是纯粹的指针。

您必须将程序准备为正常的外部,模块或F2008甚至内部程序(有一些限制)并且只需指向它:

    f => my_function

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

答案 1 :(得分: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
相关问题