Re: Reference to derived type element by index?



Rob Crain <r.a.crain@xxxxxxxxxxxx> wrote:

I have a derived type, e.g.

type circle_datatype
real :: radius
real :: x
real :: y
real :: z
character(len=*) :: circle_label
endtype circle_datatype
type(circle_datatype) :: circle

You have a compiler that let you get by with that? It shouldn't.
Unrelated to your question, but the len=* is invalid Fortran.

and want to refer to the individual elements via some indexing scheme,
say in this example I want to change the value of circle%radius I would
use index #1, or the z-coordinate I would use #4. Is there some method
by which this is possible?

Not directly, no. You can sometimes play games with equivalence, but
that has a lot of "issues" and is very limitting. For example, the
simplest games aren't standard conforming or portable unless the derived
type meets the stringent conditions for being a numeric sequence type
(the conditions are considerably more stringent than you'd guess from
the term).

In some cases you might be able to get by with an accessor function,
with a select case construct buried in the function. Thus you could have
a notation like

component(circle,3)

where component is the function. That will only work well when al the
components you want to access have the same type.

--
Richard Maine | Good judgement comes from experience;
email: last name at domain . net | experience comes from bad judgement.
domain: summertriangle | -- Mark Twain
.