For example, I want to write a function of mean
. Just like the sum
, it could take any dimension (1,2,3,4,5, ...)
of an array, and could either return a scalar or an array. Does elemental function could do this, or should I use an interface ?
1 Like
To take an array with any number of dimensions you can use assumed rank arrays real :: a(..)
and the select rank(a)
construct. But as soon as you want to pass different data types and have an optional dim
argument I think you have to use an interface.
Even if there was a way to solve this in another way, an interface should be much cleaner and easier to read.
However, I am not that experienced, maybe someone knows a better solution.
1 Like
You would have to use an interface and various specific implementations:
- If you specify a particular dimension, you would get back an array of a dimension one less than the input.
- If you pass a one-dimensional array or no dimension at all, the result is a scalar and that is a different thing.
- And sum and others also accept a mask.
It is certainly not impossible to write such a function with an analoguous interface as sum, but you will need a whole number of specific implementations.
For the dimensionality, have a look at fypp, as used in stdlib.
1 Like