elm-community / maybe-extra

Convenience functions for working with Maybe.

Home Page:http://package.elm-lang.org/packages/elm-community/maybe-extra/latest

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

add `filter`

pzp1997 opened this issue · comments

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