Print

Print


>  > > 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.  

I would say it is an improvement. With PACK, you have to write
        allocate (B_ptr(count(Mask)))
        B_Ptr = PACK(A, Mask)

> 
> 2) The result is an array:
> 	integer, dimension(2) :: B
> 	B = MYPACK(A, Mask)
> 
> This is valid FORTRAN.

This is valid only if Mask has 2 true elements.

> 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. 

The proper way to use it in as in 1) above, where the allocated memory 
is used as the target.


Hope this helps.

John Reid. 


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%