How to store a set of functions into a Fortran array

↘锁芯ラ 提交于 2021-02-04 21:44:34

问题


As we know that function name can be treated as parameters to pass in/out by other subroutines. I wonder if we have any tricks to save a list of functions into an array, which would be passed in and out for process.

!-------for example. At somewhere we set any array

type(Idonotknow)::Farray(N)

Then set the value:

Farray(1)%any=>fun1

Farray(2)%any=>fun2

...
Farray(N)%any=>funN

where fun1,fun2...funN are something like

Function fun1(input)
         implicit none
         statements 
End Function

Finally we can call them

do i = 1, N
  Call F(i)%any(input)
enddo

回答1:


Firstly you should create a type that contain only a procedure pointer that doesn't pass any argument. and then create an array of that type.

Example:

program test_func_array
   implicit none

   type pp
    procedure(func) ,pointer ,nopass :: f =>null()
   end type pp

   interface
      function func(x)
         real :: func
         real, intent (in) :: x
      end function func
   end interface

   type(pp) :: func_array(4)

   func_array(1)%f => exp
   func_array(2)%f => tan
   func_array(3)%f => cos
   func_array(4)%f => sin

   print*,func_array(1)%f(1.)
   print*,func_array(2)%f(1.)
   print*,func_array(3)%f(0.)
   print*,func_array(4)%f(0.)  

end program test_func_array


来源:https://stackoverflow.com/questions/44867531/how-to-store-a-set-of-functions-into-a-fortran-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!