首页 > 解决方案 > 从集合更新记录字段

问题描述

这些天我在玩 Elm,但我坚持了一个简单的案例,我想更新一个记录字段。我的代码是这样的:

-- MODEL


initialModel : Model
initialModel =
    { selectedLanguage = "german"
    , allCards = Card.cards
    }


type alias Msg =
    { description : String
    , data : String
    , id : String
    }

更新功能

update : Msg -> Model -> Model
update msg model =
    case List.head (model.allCards) of
        Just card ->
            { card | fliped = True }
        Nothing -> model

但我看到了这个:

Something is off with the 1st branch of this `case` expression:

50|             { card | fliped = True }
                ^^^^^^^^^^^^^^^^^^^^^^^^
The 1st branch is a record of type:

    { back : String, fliped : Bool, front : String, id : String }

But the type annotation on `update` says it should be:

    Model

Hint: Seems like a record field typo. Maybe back should be allCards?

Hint: Can more type annotations be added? Type annotations always help me give
more specific messages, and I think they could help a lot in this case!
Detected errors in 1 module.

我想我应该总是update像我的类型所说的那样从函数返回一个模型,但不知道如何。这里有什么建议吗?

标签: recordelm

解决方案


您也将更新该allCards字段model。如果前者返回一个列表而不仅仅是一张卡片,您可以将卡片更新嵌套在模型更新中:

update : Msg -> Model -> Model
update msg model =
    { model
    | allCards =
        case model.allCards of
            card :: rest ->
                { card | fliped = True } :: rest

            [] ->
                []
    }

或者,allCards如果您愿意,可以将新名称绑定到名称:

update : Msg -> Model -> Model
update msg model =
    let
        newAllCards =
            case model.allCards of
                card :: rest ->
                    { card | fliped = True } :: rest

                [] ->
                    []
    in
    { model | allCards = newAllCards }

我在这里直接在列表上进行模式匹配,而不是使用List.head,因为这也给了我列表的其余部分,我不必处理中间Maybe值(实际上是两个,因为也List.tail返回 a Maybe)。card::rest分支命中 ifallCards包含至少一张卡片,因此唯一剩下的情况是因此,[]这很容易处理。

另外,flipped用两个ps 拼写;)


推荐阅读