Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

fortran90 - Direct indexing of function return value in Fortran

Is there possibility to use indexing directly on a function's return value? Something like this:

readStr()(2:5)

where readStr() is a function which returns a character string or an array. In many other languages it is quite possible, but what about Fortran? The syntax in my example of course does not compile. Is there any other syntax to be used?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

No, that is not possible in Fortran. You could, however, alter your function to take an additional index array that determines which elements are returned. This example illustrates this possibility using an interface to allow for an optional specification of the indices (simplified greatly thanks to the comment by 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...