Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.

how to iterate on components of a derived type

Xj_Kong
Novice
508 Views

! Just curious, is it possible to have any algorithm to iterate on V1 to V10?

! In a way like ...

do i=1,10

V_current=MyList%V

end do

TYPE::MyList
  integer::V1,V2,V3,V4,V5,V6,V7,V8,V9,V10
END TYPE MyList

0 Kudos
5 Replies
jimdempseyatthecove
Honored Contributor III
508 Views

 

do i=1,10

V_current=MyList%V(i) ! us () not []

end do
! TYPE has to be declared first

TYPE::MyList
  integer::V(10) ! array of V
! or you can use
  integer, dimension(10) :: X ! equivalent to X(10)
END TYPE MyList

Jim Dempsey

0 Kudos
Xj_Kong
Novice
508 Views

Yes, but this only works for uniform data type. I expect we can walk into components by pointer or something inside the TYPE structure stored memory.

Thanks anyway.

0 Kudos
mecej4
Honored Contributor III
508 Views

You can do something along the lines of what you want using UNION, which is a nonstandard but fairly common extension in Fortran. Note that it is similar to and has some of the same drawbacks as EQUIVALENCE, and using UNION may make your program less portable and harder to debug. What do you really want to do with such code? Note this warning from the IFort manual:

With union declarations, only one map declaration within a union declaration can be associated at any point in time with the storage location that they share. Whenever a field within another map declaration in the same union declaration is referenced in your program, the fields in the prior map declaration become undefined and are succeeded by the fields in the map declaration containing the newly referenced field.

program listproc
TYPE MyListType
  SEQUENCE
  UNION
    MAP
      integer :: V1,V2,V3,V4,V5,V6,V7,V8,V9,V10
    END MAP
    MAP
    integer :: V(10)
    END MAP
  END UNION
END TYPE MyListType

type(MyListType),target :: MLT
integer :: i

MLT%V=[(i,i=1,10)]
write(*,'(5I4)')MLT%V1,MLT%V3,MLT%V5,MLT%V7,MLT%V9

MLT%V2=252
MLT%V4=254
MLT%V6=256
MLT%V8=258
write(*,'(10I4)')MLT%V

end program

 

0 Kudos
jimdempseyatthecove
Honored Contributor III
508 Views

Then one possibility is to construct a polymorphic data type able to assume a form the desired types (with operator functions).

Next, construct a type with an allocatable array of the above polymorphic types.

Now you can have a type with an indefinite number of different types, as well as an array (population) of said extensible polymorphic types.

The container type containing the array of polymorphic type may need the type walker to do some operation on each of the types in the array of polymorphic types.

Jim Dempsey

0 Kudos
Xj_Kong
Novice
508 Views

Using UNION is one option, but it still makes things more complexed than just writing more HARD text.

Thanks a lot. I won't dig into this anymore.

Regards,Kong

0 Kudos
Reply