更新集合中的记录字段

Update record field from Collection

这几天我在玩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.

我想我应该总是 return 来自 update 的模型像我的类型所说的那样运行,但不知道如何实现。有什么建议吗?

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

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 returns 还有 Maybe)。如果 allCards 包含至少一张牌,则 card::rest 分支命中,因此唯一剩下的情况是 [],这很容易处理。

此外,flipped 拼写为两个 ps ;)