Fortran 中函数返回值的直接索引

ham*_*tar 6 fortran fortran90 fortran2003

是否有可能直接在函数的返回值上使用索引?像这样的东西:

readStr()(2:5)
Run Code Online (Sandbox Code Playgroud)

wherereadStr()是一个返回字符串或数组的函数。在许多其他语言中,这是很有可能的,但是 Fortran 呢?我的示例中的语法当然无法编译。有没有其他语法可以使用?

Ale*_*ogt 5

不,这在 Fortran 中是不可能的。但是,您可以更改您的函数以采用额外的索引数组来确定返回哪些元素。此示例使用接口说明了这种可能性,以允许索引的可选规范(由于 IanH 的评论而大大简化):

module test_mod
  implicit none

  contains

  function squareOpt( arr, idx ) result(res)
    real, intent(in)              :: arr(:)
    integer, intent(in), optional :: idx(:)
    real,allocatable              :: res( : )
    real                          :: res_( size(arr) )
    integer                       :: stat

    ! Calculate as before
    res_ = arr*arr

    if ( present(idx) ) then
      ! Take the sub-set    
      allocate( res(size(idx)), stat=stat )
      if ( stat /= 0 ) stop 'Cannot allocate memory!'

      res = res_(idx)
    else
      ! Take the the whole array    
      allocate( res(size(arr)), stat=stat )
      if ( stat /= 0 ) stop 'Cannot allocate memory!'

      res = res_
    endif

  end function
end module

program test
  use test_mod
  implicit none

  real    :: arr(4)
  integer :: idx(2)

  arr = [ 1., 2., 3., 4. ]
  idx = [ 2, 3]

  print *, 'w/o indices',squareOpt(arr)
  print *, 'w/  indices',squareOpt(arr, idx)
end program
Run Code Online (Sandbox Code Playgroud)

  • 要使用可选变量的值来确定函数结果的特征,请使结果可分配并延迟特征。 (2认同)