【问题标题】:Direct indexing of function return value in FortranFortran 中函数返回值的直接索引
【发布时间】:2020-06-02 07:23:31
【问题描述】:

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

readStr()(2:5)

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

【问题讨论】:

    标签: fortran fortran90 fortran2003


    【解决方案1】:

    不,这在 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
    

    【讨论】:

    • 让函数获得一个额外的索引参数是一个很好的方法。该参数可以是“可选”参数,我认为您编写的两个函数可以合并为一个。我要试试这个。
    • 要使用可选变量的值来确定函数结果的特征,使结果可分配并延迟特征。
    • @IanH 谢谢!我不知道......我会改变我的答案。
    【解决方案2】:

    没有。

    但是,如果它让您感到困扰,您可以编写自己的用户定义函数和运算符来获得类似的结果,而无需将函数引用的结果存储在单独的变量中。

    【讨论】:

    • 谢谢。我想知道是否存在我缺少的语法。在这种情况下,根据您和 Alexander @Vogt 的回答,当性能可能受到严重影响时,我将让函数接收一个额外的“可选”索引参数。
    【解决方案3】:

    如果您使用associate,您可以避免声明另一个变量。它是否比临时变量更好或更清晰必须由用户决定。结果无论如何都必须存储在某个地方。

     associate(str=>readStr())
       print *, str(2:5)
     end associate
    

    对于这种可能很长的字符串的特定情况,它不会很有用,但对于在此处作为重复链接的其他类似情况可能更有用。

    【讨论】:

      猜你喜欢
      • 2010-11-22
      • 2016-10-23
      • 1970-01-01
      • 1970-01-01
      • 2013-08-19
      • 2011-04-19
      • 1970-01-01
      相关资源
      最近更新 更多