j3-fortran / fortran_proposals

Proposals for the Fortran Standard Committee
175 stars 14 forks source link

Optional conditional reallocation in allocate (`reallocatable` attribute) #318

Open certik opened 8 months ago

certik commented 8 months ago

First requested at https://fortran-lang.discourse.group/t/is-allocate-a-function-or-subroutine/2771/6. See also https://fortran-lang.discourse.group/t/reallocatable-attribute/5914 for a more general approach.

It would simplify a lot of my code if allocate() had an optional argument to trigger conditional reallocation of an existing array. Say something like

allocate( a(lb:ub), conditional_reallocation=.true. )

If a(:) is already allocated with lower bound lb and upper bound ub, then nothing happens, the array is unchanged. If a(:) is already allocated with the correct size but with different bounds, then the bounds are changed but the contents of the array would remain unchanged. If a(:) is already allocated but with a different size, then it is deallocated and reallocated with the new size and bounds. All of this can be done now with some trickery, but these common operations should be a standard part of the language.

shahmoradi commented 8 months ago

Even better, in my opinion, would be a new statement resize() without further complicating the existing allocate() interface, which would also avoid the need for the lengthy optional argument conditional_reallocation. This facility was so crucial and helpful that it justified the excruciating effort of writing 20,000 extra lines of code in our library to allow generic resizing of intrinsic type objects and custom containers.

jalvesz commented 8 months ago

I'll bring here some of the comments made on the forum.

So, my 2 cents here are: better to integrate reallocation within the already existing allocate. Does an extra argument is required? I think not but would honestly want to see a practical reason for which it would be really needed.

PierUgit commented 6 months ago

Here is a proposal, with a demonstration code: https://github.com/PierUgit/enhanced-allocatables

I have defined a resize routine that would be a new statement if integrated in the language, but it could be as well an extension of the current allocate (with some drawbacks in my opinion)