It would be awesome if elemental
(and perhaps pure
) functions could be used with subarray indexing (which is already great in Fortran), that would save a lot of unnecessary temporary “index” arrays. I’m not sure about anyone else on this forum, but as I use elemental
functions as much as possible, I also find myself also having very often to “prepare” index arrays to feed such functions
Imagine something like:
! This is a dumb integer power
elemental function int_power(x,i) result(x_pow_i)
real, intent(in) :: x
integer, intent(in) :: i
real :: x2,x_pow_i
select case (i)
case (0); x_pow_i = 0.0
case (1); x_pow_i = x
case (2); x_pow_i = x*x
case (3); x_pow_i = x*x*x
case (4); x2 = x*x; x_pow_i = x2*x2
case default; x_pow_i = x**i
end select
end function int_power
Now, if you want several powers you need to do
integer, allocatable :: even(:)
real, allocatable :: powers(:)
even = [0,2,4,6,8]
powers = int_power(2.0,even)
! or
powers = int_power(2.0,[(j,j=0,8,2)])
While with subarray-index-enabled functions, it would be simply
powers = int_power(2.0,0:8:2)
Simple, optimizeable, readable, concise. I would use that a lot.
The simplest usage would be to return an array with those same indices
elemental integer function self(i) result(j)
integer, intent(in) :: i
j = i
end function self
which could be used like:
integer, allocatable :: i(:)
i = self(-53:103:2)
print *, i ! -53 -51 -49 -47 .....
I guess the same restrictions as to working with elemental functions would apply, that probably wouldn’t be hard to implement in current compilers. Thoughts?