Reduction Functions

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.

1 Like

Fortran 2018 added REDUCE:

result = reduce(array, operation[, mask][, identity][, ordered])
result = reduce(array, operation, dim[, mask][, identity][, ordered])

Not sure if the median can fit into this interface.

1 Like

operation seems to be very limited, can only reduce two items at a time.
A function would be much more flexible, plus it would give a nicer frontend.

I think this would make a really nice addition, especially for rank-agnostic treatment of multidimensional arrays. I have personally implemented this feature, along with other utilities, with the current language elements using derived types. The following is a small library that I use in projects requiring rank-agnostic array processing. Although I designed the library to be useful mainly for myself, I thought it would be worth sharing it here.

As an aside, I would like to point out that many routines in stdlib, specially numerical integration routines, may be regarded as reduction functions, so there would be straightforward uses for the proposed reduction attribute.

2 Likes