John Reid writes:
> >
> > There seems to be a restriction that the result of an array-valued
> > function must be an explicit-shape array or a pointer. Given that
> > restriction, how would one write a function with behavior similar to
> > the F90 PACK intrinsic? In many functions, the shape of the result is
> > related to the shape(s) of the argument(s). The case of PACK is an
> > exception - the shape of the result cannot be declared as a function
> > of the arguments.
> >
>
> This is precisely why pointer results are permitted. You work out
> how large the array needs to be, allocate it, and then assign its
> values.
>
> John Reid.
Thanks for the response. I considered how a pointer result might be
used, however I do not see how that solves the problem. If I
understand use of F90 pointers, then a function which returns a
pointer to an array will not emulate the F90 PACK intrinsic.
Assume this function declaration:
module mypack_module
contains
function MYPACK(ARRAY, MASK)
implicit none
integer, dimension(:) :: ARRAY
logical, dimension(:) :: MASK
integer, dimension(:), pointer :: mypack <-- result is a pointer
integer :: i, j
allocate(mypack(count(mask)))
j = 1
do i = 1, SIZE(ARRAY)
if (MASK(i)) then
mypack(j) = ARRAY(i)
j = j+1
end if
end do
return
end function MYPACK
end module mypack_module
Then I have two ways to use the function MYPACK.
1) The result is a pointer to an array:
integer, dimension(:), pointer :: B_Ptr
B_Ptr => MYPACK(A, Mask)
In this case, the LHS is a pointer to an array, rather than an array.
This is useful in many cases, but the behavior is different from
PACK.
2) The result is an array:
integer, dimension(2) :: B
B = MYPACK(A, Mask)
This is valid FORTRAN. However, MYPACK had to allocate an array to
hold the result. That result is then copied into the user array B.
The memory that was allocated inside MYPACK is lost.
So I still don't know how to write a routine which behaves the way the
intrinsic PACK behaves. Am I not understanding FORTRAN pointers?
thanks,
-robert
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|