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?
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 Nothing
s. Using the identity
function, will therefore effectively just unwrap and filter out the Nothing
s 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 ]