在将两个案例语句嵌套在榆树中时,我可以避免重复代码吗?

发布于 2025-02-01 08:38:56 字数 580 浏览 3 评论 0原文

我正在将可能的字符串转换为date。我已经将Aliased date键入出生日期以进行可读性。

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

在此嵌套情况下,我必须调用DefaultBirthdate两次可能的“失败”。

有或不使用案例,是否有其他方法?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烟若柳尘 2025-02-08 08:38:56

您可以使用 < < < /a>:

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

        _ ->
            defaultBirthdate

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文