Note that function results are declared to be array- valued with ordinary declaration statements, as if the function name is an ordinary variable (as indeed it is within the body of the function). Though automatic arrays may be the most useful form for user-defined array-valued functions, any other form is also valid: explicit-shape array, allocatable array, pointer array. These are also declared and used in the procedure as if the function name were just another variable. The main additional requirement is that the array value must be fully defined before returning from an execution of the function. On the other end of things, the interfaces of array-valued functions must be explicit where such functions are used, so that the caller knows that it's dealing with a function that is array-valued.
A simple example of an array-valued function definition will complete this section. Suppose that the partial sums of a one-dimensional array of n elements are needed in an array expression-that is, the kth value needed is sum(P(1:k)). An array-valued function is ideal for delivering the requisite set of values (although in this simple case it might be almost as good to use the array constructor in the expression rather than the call to Partial_sums):
function Partial_sums(P) real P(:) ! Assumed-shape dummy array real Partial_sums(size(P)) ! The partial sums to be returned integer k Partial_sums = (/(sum(P(1:k),k=1,size(P))/) ! This is functionally equivalent to ! do k=1,size(P) ! Partial_sums(k) = sum(P(1:k)) ! end do ! but the do loop specifies a set of sequential ! computations rather than parallel computations end function Partial_sums
The following more complicated examples of data parallel computations are also configured to deliver results as user-defined array-valued functions.