Component of derived type function value

Recently I was surprised by the commented-out statement in the program below being disallowed by gfortran, ifort and ifx. They were all correct: Intel’s error message “The leftmost part-ref in a data-ref can not be a function reference.” showed me that log(minus1)%im was being treated as if it were a component of a derived type, and F2023 prohibits the derived type being a function reference. This prohibition is reminiscent of the F66 prohibition of things like X*Y in lists to be written by WRITE statements, forcing one to invent and use a new variable e.g. XY=X*Y and then write XY. F77 removed that annoying prohibition. Could F202Y remove the similarly annoying prohibition of components of derived types which are function values?

  implicit none
  complex,parameter :: minus1 = -1, z = log(minus1)
!  print *,log(minus1)%im
  print *,z%im
end program

You can’t write

log(minus1)%im

but you can write

aimag(log(minus1))

A similar request has been to allow subscripting of expressions when they are array-valued. The answer has been a suggestion to ASSOCIATE the expression with a variable and subscript that variable. One could similarly ASSOCIATE an expression returning a complex variable or a derived type to a variable and then access fields of the associated variable with the usual %.

The code

  implicit none
  complex, parameter :: minus1 = -1, z = log(minus1)
!  print *,log(minus1)%im
  print*,z%im
  print*,aimag(log(minus1))
  associate (x => log(minus1))
     print*,x
     print*,aimag(x)
!     print*,x%im ! gfortran says Error: Symbol 'x' at (1) has no IMPLICIT type
  end associate
end program

gives

   3.14159274    
   3.14159274    
             (0.00000000,3.14159274)
   3.14159274

with gfortran 13.0.0 20221218. I think the last commented out line should also work and will test it with gfortran 14 on a different computer.

@Beliavsky is of course right about aimag being usable in circumstances where
%im is not. Metcalf et al. in Modern Fortran Explained (2023) said on p.23 that the real and imaginary parts of a complex variable are accessible, less conveniently, by the intrinsic functions real and aimag. My suggestion was given in the hope that F202Y will allow a more convenient method in the general case of f(x)%comp, where f is a function whose value is of a user-defined derived type, and comp is a component of that derived type. The original example using %im merely allowed the point to be made by a much shorter program.

Even gfortran 14.0.1 20240121 refuses to compile print*,x%im in the previous code. Intel Fortran allows it. I think this is a bug in gfortran.

If it was not a bug, then the program would not be able to do anything with x, especially not printing it as a complex number. (There was a connection outage here, so I did not finish my sentence)

1 Like