What would be a good name for this function?

foo : List (Maybe a) -> Maybe (List a)
foo bar =
    if List.member Nothing bar then
        Nothing
    else 
        Just <| List.filterMap identity bar

See also https://elm-notebook.org/open/killi-listofmaybestomaybelist

1 Like

The maybe-extra package calls it combine: Maybe.Extra - maybe-extra 5.3.0

Same in result-extra: Result.Extra - result-extra 2.4.0

1 Like

thank you @lydell and @MartinS, that’s what I was looking for.
The related function traverse also seems very useful.

A related question, what’s the reasoning for returning Just [] instead of Nothing ?
In my first implementation I tended towards Nothing instead of empty list, but I’m not sure what implications that would have in practice. Do you have any experience with use cases where it’s actually useful to be able to distinguish Just [] from Nothing ?

I assume you’re talking about Maybe.Extra.combine [] being Just []? I don’t think there’s any other case that could return Just [].

This follows from the description of the functionality. If there are zero elements in the list, then every Maybe in the list is present, and the method returns Just. Since this decision really only affects one input, a case could be made for either return value, but I think Just [] makes sense. In this case, Nothing means “something was missing from the list”.

1 Like

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.