Proposal for `toMaybeList` function
c0m3tx opened this issue · comments
Often times, when writing code for the UI, we get a list of elements to show. They have to be shown only if at least one element is available, so it would be useful to have a function which converts a List a
in a Maybe (List a)
:
- if
list
has no elements, returnsNothing
- if
list
has at least one element, returnsJust list
This allows, for instance
renderMetadata : List String -> Html msg
renderMetadata meta =
meta
|> List.toMaybeList
|> Maybe.map renderMetadataBlock -- this function works on a proper list of strings, maybe builds some container which should not be rendered otherwise, etc
|> Maybe.withDefault (text "No metadata set")
The code we currently use for this function is quite simple, and we believe it may be a nice addition to this lib. As far as we know, currently there is no way to achieve this using what is currently available.
toMaybeList : List a -> Maybe (List a)
toMaybeList list =
if List.isEmpty list then
Nothing
else
Just list
I will do the implementation and open a PR, if you feel this could be useful 😄
Some of our collegues brought to our attention that this implementation would make the type system inconsistent, in some way. We could have a Just []
and we would be therefore unable to ensure that the inner list has at least one element. A better signature for this function would be toMaybeList : List a -> Maybe (a, List a)
, which is exactly what uncons
does. We decided that correctness is more important, and we removed all instances of this function from our code 😄
Makes sense! Yes, it does seem like the correctness of uncons
is ideal. Thanks for the time and consideration you put into this.