Re: parametrized derived types vs. allocatable components

On 1 Dez., 18:18, nos...@xxxxxxxxxxxxx (Richard Maine) wrote:
m <mreste...@xxxxxxxxx> wrote:
OK, thank you. Would it then be possible to simplify the code as

type tb(d)
integer, len :: d
real :: x(d)
end type tb
type(tb(:)), allocatable :: bvec(:) ! ???

Not quite that way, but close... and simpler. You can't allocate the
type and shape of bvec separately. That would be a lot like having a 2-D
array and allocating the number of rows and columns separately.
But you can do it all together as


Very nice, thank you!

In this specific case I prefer PDT because it emphasizes:
1) all the elements of the array have the same "LEN"
2) if there are many components, as in
type tb(d)
integer, len :: d
real :: position(d)
real :: velocity(d)
end type tb
it's clear that their sizes are not independent.

Good points. That does prompt me to mention another alternative. When I
have multiple arrays that are inherently the same size like that, it is
often because they are describing the properties of an array of objects.
In that case, I at least consider making a derived type for a single one
of the objects and having an array of that derived type, as in

type tb_scalar
real :: position
real :: velocity
end type
type(tb_scalar), allocatable :: b(:)

Your case adds an extra rank, but it seems to me that it could be done
exactly that way - by making it a 2-D array as in

type(tb_scalar), allocatable :: b(:,:)

There can be reasons why this won't work out well. Notably, it doesn't
fit if your tb has some components that are different sizes (or are
scalar), as in

type :: tb(d)
integer, len :: d
integer :: some_scalar_component
real :: position(d)
real :: velocity(d)
end type tb

Yes, I would like to do something along this line, combining
components of size d with others of size d+1 and scalar components,
but anyway I'm still looking for the final layout; thank you for all
the suggestions.