IMHO, Fortran would greatly benefit from a feature I would call reduction function. There are some intrinsic reduction functions (e.g. sum
, count
, minval
) which reduce arbitrary arrays along a specified dimension, or the array as a whole.
My suggestion is a function attribute, called reduction
, which creates an elemental function (kind of) which allows rank-1 arrays as dummy arguments, but has a scalar return value.
For example, when defining a reduction function
the compiler could add a hidden, optional dummy argument, called dim
.
When dim
isn’t specified when the function gets called, then all elements of the array are passed as rank-1 array to the reduction function
. When dim
is specified, all array slices along this dimension are passed to the reduction function
and reduced to an array of rank (n-1).
reduction function median(array) result(m)
real, intent(in) :: array(:)
real :: m
! sort array and pick median value
end function median
a = reshape([1., 2., 3., 4., 5., 6., 7., 8., 9.], [3, 3])
print *, median(a) ! -> 5.
print *, median(a, dim=1) ! -> [2., 5., 8.]
print *, median(a, dim=2) ! -> [4., 5., 6.]
Today, without this feature, it requires an interface for every possible rank of an array.