2

I have a derived type array, where the derived types can also be arrays. Is there any way to sum over elements without resorting to a do loop?

program main

   type t_couple
      real :: income(2) = 5
   end type t_couple

   type(t_couple) :: couple(2)

   print *, " sum 1 ", sum(couple(1)%income)  ! works fine
   print *, " sum 2 ", sum(couple%income)     ! doesn't work

end program main

%F90-E-ERROR, A component cannot be an array if the encompassing structure is an array.

Of course we have all seen this error message many times and can write a do loop to solve this, but I'm wondering if there is a simpler and more concise way?

0

1 Answer 1

1

You could use an implicit loop:

print *, " sum 2 ", sum( [( couple(i)%income, i=1,size(couple))] )
Sign up to request clarification or add additional context in comments.

2 Comments

Well, +1 for doing it on one line but it's still a loop... But probably there is no way to do it without a loop.
@JohnE At least I don't know of any other way...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.