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 ]
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
)
[]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With