如何从自定义类型的多个变体中提取值?

问题描述 投票:1回答:1

我有类似的,

type Post 
    = Blog String String
    | Announcement String String

和功能一样,

upcaseTitle : Post -> Post
upcaseTitle post =
    case post of
        Blog title body ->
            { post | title = String.toUpper title }
        Announcement title body ->
            { post | title = String.toUpper title }

我想写代码,

upcaseTitle : Post -> Post
upcaseTitle post =
    case post of
        Post title body ->
            { post | title = String.toUpper title }

我想在我的case语句中添加一个与所有Post类型匹配的子句,并提取常见的Stringtitle,因为它在我的union类型的所有变体中共享。

榆树有可能吗?

pattern-matching elm algebraic-data-types
1个回答
6
投票

不,不可能。在其他一些语言中,这可以使用or-patterns实现(即使这样你仍然需要枚举和解构每个变体,但它们可以共享一个单体),但Elm旨在成为一种比那些更简单的语言。

一种选择是将公共分支体提取为函数:

upcaseTitle : Post -> Post
upcaseTitle post =
    let
        setTitle title =
            { post | title = String.toUpper title }
    in
    case post of
        Blog title body ->
            setTitle title

        Announcement title body ->
            setTitle title

另一个是定义一个单独的函数来提取标题:

getTitle : Post -> String
getTitle post =
    case post of
        Blog title body ->
            title

        Announcement title body ->
            title

upcaseTitle : Post -> Post
upcaseTitle post =
    { post | title = String.toUpper (getTitle post) }

但是,如果您的自定义类型的每个变体都相同,那么我首先会质疑该类型的设计。也许最好使用一个记录,其中帖子类型只是一个字段而不是?

type PostType
    = Blog
    | Announcement

type Post =
    { title : String
    , body : String
    , postType : PostType
    }
© www.soinside.com 2019 - 2024. All rights reserved.