Can I avoid repeated code when nesting two case statements in Elm?

Viewed 43

I'm converting a Maybe String into a Date. I've type aliased Date as Birthdate for readability.

birthdate_from_url : Url.Url -> Birthdate
birthdate_from_url url =
    case url.query of
        Just query ->
            case Date.fromIsoString query of 
                Ok birthdate ->
                    birthdate

                Err _ ->
                    defaultBirthdate

        Nothing ->
            defaultBirthdate

With this nested case I'm having to call defaultBirthdate twice for each of the possible "failures".

Is there an alternative approach with or without the use of case?

1 Answers

You could use Maybe.map:

birthdate_from_url : Url.Url -> Birthdate
birthdate_from_url url =
    case url.query |> Maybe.map Date.fromIsoString of
        Just (Ok birthdate) ->
            birthdate

        _ ->
            defaultBirthdate
Related