Reputation: 4426
In Fortran, is there any way to declare an "array of allocatable arrays", that doesn't require wrapping the allocatable arrays into a derived type?
My main use-case would be to allow invoking a function with an array of variable-length strings, i.e. I am looking for a type signature matching the literal
["Hello", &
"World.", &
"How are you?"]
In Fortran strings are natively represented as fixed-size character arrays, padded with blanks on the right. Arrays of strings are normally represented as arrays of (equal-length) character arrays, which I assume is in order to make them behave like a matrix of characters.
However, this also means that doing something like
CALL mySubroutine(["Hello","World.","How are you?"])
will result in a compiler error like
Error: Different CHARACTER lengths (5/4) in array constructor at (1)
A commonly suggested workaround (see e.g. Return an array of strings of different length in Fortran) is to use an array of derived types instead, e.g.
TYPE string
CHARACTER(LEN=:), ALLOCATABLE :: chars
END type string
! ...
CALL myStringSubroutine([string("Hello"), &
string("World."), &
string("How are you?")])
However, since there is no standardized string
type of this kind, I am much more frequently seeing APIs using natively supported "workarounds" such as using fixed-size character strings, and trimming them when used. In this case the invocation would look like
CALL myFixedSubroutine(["Hello ", &
"World. ", &
"How are you?"])
While this is no problem in principle, it can become awkward and inefficient, if one of the strings is much longer than the others. It also has implications for version control, where now changing "... you?"
to "... you??"
means that the padding of the other lines has to be changed, creating spurious diffs.
(In the comments, a suggestion was given that at least automates the whitespace-padding.)
Upvotes: 2
Views: 225
Reputation: 21451
No, there is no way bar the wrapper type.
A fundamental concept in the language is that elements within an array may only vary in value. The allocation status of an object is not part of the value of that object.
(The allocation status of a component is part of the value of the object that has the component.)
A varying length string type is described in Part 2 of the Fortran standard.
Upvotes: 2