从集合更新记录字段

时间:2019-09-13 19:11:17

标签: record elm

这些天我和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函数返回一个模型,但是不能弄清楚怎么做。这里有什么建议吗?

1 个答案:

答案 0 :(得分:4)

您还将更新allCards的{​​{1}}字段。如果前者返回列表而不是单张卡,则可以将卡更新嵌套在模型更新中:

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

此外,[]的拼写是两个flipped;)