0

In a language like python, I can pass functions like an object as an argument for other functions. Is there an equivalent syntax in fortran?

Python example:

def first_func():
    print('hello world')

def second_func():
    print('HELLO WORLD')

def third_func(f):
    f()

third_func(first_func)
third_func(second_func)

So it would print out:

$> hello world
$> HELLO WORLD

I understand that in fortran I could pass a reference number to the subroutine, ie 1 results in one function and 2 results in another. However, what I am asking is if there is a way to pass the identifier for the function (ie if I wrote real function f(x), is there a way I could pass f to the subroutine as an argument, while at a different time, pass a different function real function g(x) as an argument?

Like so:

subroutine loop_funcs(func, max_iter)
    real, intent(in) :: function func
    integer, intent(in) :: max_iter
    do i = 1, max_iter
        func(i)
    end do
end subroutine loop_funcs
  • Have you tried `real, intent(in) :: func`? Note, however, that `func(i)` cannot appear by itself. You're saying it's a real function so you must use it in an expression. – francescalus Sep 19 '22 at 20:01
  • The linked question is about subroutines but it is really the same, with the only difference having to declare the return type for the external ones - which you should avoid. – Vladimir F Героям слава Sep 19 '22 at 20:04

0 Answers0