Christopher A. Wong
Christopher A. Wong

Reputation: 323

Fortran: How to make multiple procedures share the same procedure interface

I have a code that looks like

subroutine sub1(f)
    interface
        function f(x)
            (description of f)
        end function f
    end interface

    (do something with f)
end subroutine sub1

subroutine sub2(f)
    interface
        function f(x)
            (description of f)
        end function f
    end interface

    (do something with f)
end subroutine sub2

However, the two subroutines sub1 and sub2 both use identical interfaces for the dummy function f. How do I make these two procedures share the same interface (e.g. using a module)? Do I have to use procedure pointers?

Upvotes: 1

Views: 830

Answers (1)

Javier Martín
Javier Martín

Reputation: 2605

You can define such reusable "function types" as abstract interfaces in modules:

module m
    implicit none
    abstract interface
        function der(x,y) result(yDot)
            real, intent(in) :: x, y
            real :: yDot
        end function
    end interface
end module

subroutine integrateEuler(derY,x0,xf,y)
    use m
    real, intent(in) :: x0, xf
    real, intent(inout) :: y
    procedure(der) :: derY
    ! code here
end subroutine

subroutine integrateRKF45(derY,x0,xf,y)
    use m
    real, intent(in) :: x0, xf
    real, intent(inout) :: y
    procedure(der) :: derY
    ! code here
end subroutine

Using function pointers is not necessary, but you can declare them in the same way: procedure(der), pointer :: funPtr => myFun

Upvotes: 3

Related Questions