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

I have a 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 fin the main program block? For instance.

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

    ...
end 
+4
source share
2 answers

You need an explicit interface. You can do this in several ways.

  • Explicitly in the scope module, which calls f:

    interface
      function f(A)
        implicit none
        real, intent(in) :: A(5)
        real :: f(5)
      end function
    end interface
    
  • Place the function in the host area of ​​your program 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
    
  • Put the function in the 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
    
  • Use the explicit interface from another procedure with the same arguments and return type, view, 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
    

- № 3 . ( №1 , f), , , , № 2. №4 , , .

+6

:

module so_func

    INTEGER, PARAMETER :: MAX_SIZE = 5

    TYPE MY_DATA
        INTEGER :: SIZE
        REAL, DIMENSION(MAX_SIZE) :: DATA
    ENDTYPE


contains

    FUNCTION f1(A,N) RESULT(X)
    implicit none
    INTEGER, INTENT(IN) :: N
    REAL, INTENT(IN) :: A(N)
    REAL :: X(N)
    ! ....
    X = 1.0+A
    END FUNCTION f1

    TYPE(MY_DATA) FUNCTION f2(A,N)
    implicit none
    INTEGER, INTENT(IN) :: N
    REAL, INTENT(IN) :: A(N)
    ! ....
    f2%SIZE = N
    f2%DATA(1:N) = 1.0+A
    END FUNCTION f2

    FUNCTION f3(A,N)
    implicit none
    INTEGER, INTENT(IN) :: N
    REAL, INTENT(IN) :: A(N)
    REAL :: f3(N)
    ! ....
    f3 = 1.0+A
    END FUNCTION f3

end module


program SO_RESULT
    use so_func
    implicit none
    integer, parameter :: n=5
    REAL :: A(n), y1(n), y3(n)    
    TYPE(MY_DATA) :: y2
    INTEGER :: i
    ! Variables

    A =(/ (i, i=1,n) /)

    y1 = f1(A,n)
    y2 = f2(A,n)
    y3 = f3(A,n)


end program SO_RESULT
+1

All Articles