是否有可能直接在函数的返回值上使用索引?像这样的东西:
readStr()(2:5)
其中readStr()
是一个返回字符串的函数。在许多其他语言中,这是完全可能的,但是Fortran呢?我的示例中的语法当然不会编译。还有其他语法可以使用吗?
否,在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
没有
但是如果麻烦您,您可以编写自己的用户定义的函数和运算符来获得相似的结果,而不必将函数引用的结果存储在单独的变量中。