add `filter`
pzp1997 opened this issue · comments
Palmer Paul commented
Since Maybe
is a monad we can support a filter operation over it. Here's a suitable implementation:
filter : (a -> Bool) -> Maybe a -> Maybe a
filter predicate mx =
case mx of
Just x ->
if predicate x then
mx
else
Nothing
Nothing ->
Nothing
And here is a trivial example of its utility.
oddHead : List Int -> Html msg
oddHead list =
list
|> List.head
|> Maybe.filter isOdd
|> Maybe.map toString
|> Maybe.withDefault "even"
|> Html.text
Sky Rose commented