Search code examples
algorithmlistelmoption-type

Converting List (Maybe a) to Maybe (List a) in Elm


What's a good way to convert List (Maybe a) to Maybe (List a) in Elm?

The logic is simple:

  • return Just (List a) if all items are Just a
  • otherwise, return Nothing.
Example 1:

input:  [ Just 1, Just 2, Just 3 ]
output: Just [ 1, 2, 3 ]

Example 2:

input:  [ Just 1, Nothing, Just 3 ]
output: Nothing

Can it be done easily with some of the built-in functions?

The best I came up with looks like this:

listOfMaybesToMaybeList : List (Maybe a) -> Maybe (List a)
listOfMaybesToMaybeList listOfMaybes =
    List.foldl
        (\maybeItem ->
            \maybeResultList ->
                case ( maybeItem, maybeResultList ) of
                    ( Just item, Just resultList ) ->
                        Just (List.append resultList [ item ])

                    ( _, _ ) ->
                        Nothing
        )
        (Just [])
        listOfMaybes

And what would be an appropriate name for this kind of function? As I was searching for an answer, I saw that there's a function called sequence in Haskell which seems to be doing something similar.


Solution

  • You can use the Elm Fancy Search tool and search on the function signature: List (Maybe a) -> Maybe (List a)

    The first result turns up Maybe.Extra.combine