Passing a subroutine as an arugment to another subroutine

60 views Asked by At

I am trying to pass a Fortran subroutine as an argument to another subroutine. I want to do this so I can write a general module (e.g. for root finding) where I can then define various subroutines to be called by my general subroutine, which should be reusable. This is the second Fortran code I have written and my background is in Python, so my idea of how to write code is based on how I would write Python code (this probably results in Fortran code written with bad practice, but I am trying to learn).

I have figured out how to do what I want using functions, but I want to do the same thing with subroutines.

My issue is I am unsure how to declare (not sure if that's the right word) the subroutine argument in the generic subroutine. If it were a function, it would just be, for example, real :: f, but I am unsure what the equivalent is (if one exists) for subroutines.

main.f90:

program main
    use mod1, only : sub1
    use mod2, only : sub2
    implicit none

    real :: a, b

    a = 0.2

    call sub2(sub1, a, b)

    print *, b, exp(sqrt(a))
end program main

mod1.f90 (this contains the subroutine that I want to be called from another subroutine):

module mod1
    implicit none

    public sub1
    
contains
    subroutine sub1(arg1,  arg2)
        real, intent(in) :: arg1
        real, intent(out) ::  arg2

        arg2 = sqrt(arg1)
    end subroutine sub1
end module mod1

mod2.f90 (this contains the generic subroutine that I want to be able to pass other subroutines to):

module mod2
    implicit none

    public sub2
    
contains
    subroutine sub2(other_sub, arg1,  arg2)
        ???? :: other_sub   ! this is the line I am unsure of
        real, intent(in) :: arg1
        real, intent(inout) :: arg2

        call other_sub(arg1, arg2)
        arg2 = exp(arg2)
    end subroutine sub2
end module mod2

Once I have the syntax right, I plan to compile as:

gfortran mod1.f90 mod2.f90 main.f90

I can share the equivalent Python code or Fortran with passing a function if people think it is relevant/helpful/clarifying.

0

There are 0 answers