Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

fortran - How to pass a function with multiple arguments to a subroutine that expects a function with only one argument?

I have a subroutine (minimal example)

subroutine treatfunction(f,input,output)
   external, real::f
   real, intent(in):: input
   real, intent(out):: output

   output = f(input) + f(1.0)  ! i.e. f has only one argument
end subroutine

and a function with two arguments

real function fun(x,a)
   real,intent(in)::x,a

Now for a given a fixed at runtime, I want to pass fun to treatfunction. So ideally, I would want to call something like

call treatfunction(fun(:,a=a0), input=myinput, output=myoutput)

What is the most elegant way of doing this with the Fortran2003 features gfortran-5 supports?

Of course, I could insert an optional dummy argument a in treatfunction and call f either with f(x) or f(x,a) depending on present(a) in the subroutine's body. But changing the subroutine is not elegant.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In Fortran 2008 you can pass internal functions as arguments and gfortran supports it.

 subroutine calling()

   a0 = ...
   call treatfunction(wrapper, input=myinput, output=myoutput)
 contains
   real function wrapper(x)
     real, intent(in) :: x
     wrapper = fun(x,a0)
   end function
 end subroutine

BTW, I would stay away from external it is evil, use interface blocks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...