Fortran 中函数返回值的直接索引 [英] Direct indexing of function return value in Fortran

查看:23
本文介绍了Fortran 中函数返回值的直接索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

readStr()(2:5)

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

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?

推荐答案

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

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

这篇关于Fortran 中函数返回值的直接索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆