更新 Elm 中的数据值

Update data value in Elm

我试图在重新使用之前更改对象数据值。

我有一个数据类型

type alias Definition =
    { title : String
    , description : String
    , image : String

    }

-- 使用来自API

的原始数据
    getDescription : Tag -> (Definition -> a) -> String -> Maybe Definition -> Html a
    getDescription tag msg name def =
            case def of
                Just d ->
                        div [] [
                            div [] [ text d.title ]
                            , div [] [ text d.description ]

-- trying to change description with removeDescription function      
                            , div [] [ newDescription (removeDescription d) ] 

                            ]
                Nothing ->
                    div [] [ text "name"]





newDescription : Definition -> Html a
newDescription d =
    div [] [ 
        div[] [d.title] 
        , div[] [ d.description ]        -- trying to use new description
        ]

-- 该函数失败

removeDescription : Definition -> Definition
removeDescription d = 
        { d | d.description = '' }   -- This fails 

我试过了

String.replace

但还是失败了

考虑到 Elm 确保数据不变性,甚至可以像这样更改数据吗?

如果您还发布了 Elm 的(有帮助的!)错误消息,我会更加确定,但在您的示例中,当您更新记录时,您似乎想要 description 而不是 d.description (这是用于返回其他值不变的新记录的语法糖——正如您所注意到的,Elm 具有纯度/数据不变性)。

Elm REPL 中使用您的记录类型的示例:

> d = Definition "Test" "Hello World" "0000"
{ description = "Hello World", image = "0000", title = "Test" }
    : Definition
> d2 = {d | description = ""}
{ description = "", image = "0000", title = "Test" }
    : { description : String, image : String, title : String }

Elm docs

中还有更多示例