作为输出参数的函数 [英] Function as an output argument

查看:159
本文介绍了作为输出参数的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  module fun_out 

包含

子程序指数(F,a)
接口,意图(出)

函数f(x)
真实,意图(in):: x
real :: f(2)
结束函数
结束接口
真实,意图(in):: a

F = exp(a * x)

结束子程序指数
$ b结束模块

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

解决方案

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

  procedure(name_of_interface),pointer :: f 


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

  f => my_function 

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


I want to create a subroutine that gives back a function as an output. How can I do that? I'll put an example of how I think it should be (I know it's badly written)

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

With this I should take a function from the exponential family in the output.

解决方案

You would have to return a function pointer. That can be done in Fortran 2003.

   procedure(name_of_interface), pointer :: f

You must however not expect full lexical scope closures, just pure pointers.

You must have the procedure prepared as a normal external, module or in F2008 even internal procedure (with some limitations) and just point to it:

    f => my_function

In your case you have the argument a, and you seem to want to use it a captured closure variable. It is not possible in Fortran. You either have to pass it every time to the function, or us the Functor pattern (derived type holding the captured parameters), or use an internal procedure (but that would be valid only inside its host procedure).

这篇关于作为输出参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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