Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare the type of a function that returns an array in Fortran?

Tags:

fortran

I have function that returns an array, say

function f(A)
    implicit none
    real, intent(in) :: A(5)
    real, intent(out) :: f(5)

    f = A+1
end

My question is, how can I define f in the main program unit? E.g.

program main
    implicit none
    real :: A(5)
    real, dimension(5), external :: f  ! does not work

    ...
end 
like image 331
bcf Avatar asked Jan 10 '23 15:01

bcf


1 Answers

You need an explicit interface. You can do this in a few ways.

  1. Explicitly in the scoping unit that calls f:

    interface
      function f(A)
        implicit none
        real, intent(in) :: A(5)
        real :: f(5)
      end function
    end interface
    
  2. Place the function in your program host scope as an internal function:

     program main
        ...
     contains
       function f(A)
         implicit none
         real, intent(in) :: A(5)
         real :: f(5)
    
         f = A+1
       end
     end program
    
  3. Place the function in a module:

     module A
     contains
       function f(A)
         implicit none
         real, intent(in) :: A(5)
         real :: f(5)
    
         f = A+1
       end
     end module
    
     program main
       use A
       ...
     end program
    
  4. Use the explicit interface from a different procedure with the same arguments and return type, kind and rank.

    program main
      interface
        function r5i_r5o(r5)
          implicit none
          real, intent(in) :: r5(5)
          real :: r5i_r5o(5)
        end function
      end interface
    
      procedure(r5i_r5o) :: f
      ...
    end program
    
    function f(A)
      implicit none
      real, intent(in) :: A(5)
      real :: f(5)
    
      f = A+1
    end
    

The cleanest way of doing this is option #3 using modules. This gives you the benefit of an automatic explicit interface (not needing to do option #1 everywhere you call f) and makes your function available everywhere the module is used rather than limited to a specific scoping unit as in option #2. Option #4 can be handy if you have many procedures with the same argument and return types since one explicit interface can be re-used for all of them.

like image 127
casey Avatar answered May 20 '23 01:05

casey