Pascal Le Merrer
Pascal Le Merrer

Reputation: 5981

Extract values from a list of maybes

In Elm, I have a list like:

[ Just a, Nothing, Just b]

and I want to extract from it:

[a, b]

Using List.map and pattern matching does not allow it, unless I'm wrong, because I can't return nothing when the value in the list is Nothing. How could I achieve this?

Upvotes: 6

Views: 515

Answers (2)

glennsl
glennsl

Reputation: 29116

If you don't want any extra dependencies, you can use List.filterMap with the identity function:

List.filterMap identity [ Just a, Nothing, Just b ]

filterMap looks and works a lot like map, except the mapping function should return a Maybe b instead of just a b, and will unwrap and filter out any Nothings. Using the identity function, will therefore effectively just unwrap and filter out the Nothings without actually doing any mapping.

Alternatively, you can use Maybe.Extra.values from elm-community/maybe-extra:

Maybe.Extra.values [ Just a, Nothing, Just b ]

Upvotes: 12

fayong lin
fayong lin

Reputation: 224

Usually in this case I use a helper function like this one:

extractMbVal =
    List.foldr
        (\mbVal acc ->
            case mbVal of
                Just val ->
                    val :: acc

                Nothing ->
                    acc
        )
        []

Upvotes: 2

Related Questions