Accessing array elements and member variables/procedures of function results

Something that I’ve been thinking about for a while, and which came up again on Stack Overflow recently: I think it would be nice if it were possible to access array elements and class members of function results directly, without having to create a temporary variable.

For example, consider the code:

module m
  implicit none
  type :: T
    integer :: var
    procedure :: foo
  end type

function foo(this) result(output)
  class(T), intent(in) :: this
  integer :: output
  output = 1
end function

function g() result(output)
  integer :: output(10)
  output = 1
end function

function h() result(ouptut)
  type(T) :: output
  output%var = 1
end function

subroutine main()
  type(T) :: array(10)
  write(*,*) array(1)%foo()
  write(*,*) g()(1)
  write(*,*) h()%var
  write(*,*) h()%foo()
end subroutine
end module

program p
  use m
  implicit none
  call main()
end program

The first write statement is fine; it is possible to access a member function of an array element. But the other three write statements are not allowed by the standard; it is not possible to access an array element of a function result, nor to access a member variable or member function of a function result.

I think allowing this would improve the language, by allowing a number of code patterns to be simplified. See the Stack Overflow question I linked above for one use case.

So, what does everyone think? Is there a reason this could not be allowed by a future standard? Are there downsides I haven’t thought of? Or is it already somewhere at the back of the “TODO” queue?

For what it’s worth, I couldn’t find this suggestion on Issues · j3-fortran/fortran_proposals · GitHub or elsewhere on this site, although I may well have missed it.

Related was my withdrawn proposal for Subscripting array-valued expressions as if they were arrays.

1 Like

Interesting. Yes, the two proposals are very similar.

In your reasons for withdrawing that proposal you reference a post on this forum which doesn’t seem to exist any more. Could you summarise those reasons again?