Arrays 返回具有非平凡边界的可分配数组的Fortran函数

Arrays 返回具有非平凡边界的可分配数组的Fortran函数,arrays,functional-programming,fortran,allocatable-array,Arrays,Functional Programming,Fortran,Allocatable Array,对于object,我很难理解返回可分配数组的函数背后的逻辑。我喜欢这个结构,因为它比子程序更清晰,因为fortran中的纯函数是编写干净的函数式编程代码的极好方法 假设我必须编写一个简单的函数,返回一个具有任意边界的索引数组,例如在这个程序中: program test_allocatable_functionReturn implicit none integer, allocatable :: fun(:),sub(:),noa(:) integer,

对于object,我很难理解返回可分配数组的函数背后的逻辑。我喜欢这个结构,因为它比子程序更清晰,因为fortran中的纯函数是编写干净的函数式编程代码的极好方法

假设我必须编写一个简单的函数,返回一个具有任意边界的索引数组,例如在这个程序中:

program test_allocatable_functionReturn
      implicit none

      integer, allocatable :: fun(:),sub(:),noa(:)
      integer, parameter :: low = -4
      integer, parameter :: hi  = 3

      call testsub(sub,low,hi)
      fun = testfun(low,hi)
      noa = testfun_noalloc(low,hi)

      print '(4(a,i3),a)', 'testsub:  lbound=',lbound(sub),'(expected = ',low,'), ubound=',ubound(sub),'(expected = ',hi,')'
      print '(4(a,i3),a)', 'testfun:  lbound=',lbound(fun),'(expected = ',low,'), ubound=',ubound(fun),'(expected = ',hi,')'
      print '(4(a,i3),a)', 'no alloc: lbound=',lbound(noa),'(expected = ',low,'), ubound=',ubound(noa),'(expected = ',hi,')'


      contains
             pure function testfun_noalloc(low,hi) result(array)
                integer, intent(in) :: low,hi
                integer :: array(low:hi)
                integer :: i
                 forall(i=low:hi) array(i) = i
             end function testfun_noalloc


             pure function testfun(low,hi) result(array)
                integer, allocatable :: array(:)
                integer, intent(in) :: low,hi
                integer :: i
                 allocate(array(low:hi))
                 forall(i=low:hi) array(i) = i
             end function testfun


             pure subroutine testsub(array,low,hi)
                integer, intent(out), allocatable :: array(:)
                integer, intent(in) :: low,hi
                integer :: i
                 allocate(array(low:hi))
                 forall(i=low:hi) array(i) = i
             end subroutine testsub

end program
我以三种方式实施:

  • 返回可分配数组的函数(
    testfun
  • 子例程(
    testsub
  • 返回静态数组的函数(
    testfun\u noalloc
子例程对返回数组进行操作,并正确分配它。在本例中,应返回大小为
(-4:3)
的数组。在两种实现中,函数都返回一个
(1:hi-low+1)
大小的数组:

testsub:  lbound= -4(expected =  -4), ubound=  3(expected =   3)
testfun:  lbound=  1(expected =  -4), ubound=  8(expected =   3)
no alloc: lbound=  1(expected =  -4), ubound=  8(expected =   3)
为什么会这样?我得到这样一个事实,fortran在将函数返回值分配给我的LHS数组时可能会重新分配数组,但即使如此,为什么它没有分配适当的边界?我理解在将静态数组传递给具有f2003样式的lhs重新分配的可分配数组时可能会发生这种情况,但使用可分配数组作为输入时,我希望边界信息得到保存。我是不是遗漏了什么?顺便说一句,这个例子是用gfortran 9.2.0编译的

谢谢,
Federico

正如在对相关问题的回答中所指出的,数组表达式的下界(不是整个数组)始终为1,无论该表达式中使用的数组的边界如何。明白了,谢谢-我理解其中的原因。但是,IMHO这使得使用价值大小的数组的吸引力大大降低。。。。