Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 786
Pascal Le Merrer Avatar asked Sep 06 '19 14:09

Pascal Le Merrer


2 Answers

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 ]
like image 63
glennsl Avatar answered Nov 19 '22 01:11

glennsl


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
        )
        []
like image 2
fayong lin Avatar answered Nov 19 '22 01:11

fayong lin