Description
Apologies in advance as this topic is still a bit fuzzy on my side.
The general idea is to provide some kind of safety functions to work with allocatable
variables, the most commonly used is the deferred length character variable. There is one minor annoyance, an empty deferred length character can either be an empty string or unallocated, but usually we would like it to behave consistently for this case, i.e. len(dlc)
returning zero instead of a segmentation fault when the dlc
variable is not allocated.
Adding the required additional checks is usually quite redundant, therefore providing a good and general mechanism to deal with such situations might be in scope for stdlib.
For the particular case of a deferred length character the function might look like (note that this function will create a copy of the character variable in the progress of making it safe):
!> Safely return a deferred length character
elemental function maybe(string) result(maybe_string)
character(len=:), allocatable, intent(in) :: string
character(len=maybe_len(string)) :: maybe_string
if (allocated(string)) then
maybe_string = string
else
maybe_string = ''
end if
end function maybe
!> Safely return the length of a deferred length character
elemental function maybe_len(string) result(length)
character(len=:), allocatable, intent(in) :: string
integer :: length
length = merge(len(string), 0, allocated(string))
end function maybe
Similar functions could be defined for allocatable
integers, reals and logicals if we can agree on a “neutral” element for those data types.
The naming is loosely oriented at Rust's maybe
, ok
and err
functionality, emulating something like this in stdlib would be the ultimate goal of the proposal.