record - 从集合更新记录字段
问题描述
这些天我在玩 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
像我的类型所说的那样从函数返回一个模型,但不知道如何。这里有什么建议吗?
解决方案
您也将更新该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
用两个p
s 拼写;)
推荐阅读
- r - facet_grid 中的自由色标
- javascript - 如何在圆形网格内找到一定大小的所有正方形
- php - Blade 没有渲染 Laravel
- java - 计算大写字母、小写字母、空格和其余部分(数字等)
- java - 泛型方法的问题
- google-chrome - 如何摆脱 SVG 中不需要的细边框?不同的行为(IE、Chrome 等)
- javascript - 有没有办法指定 Object.values() 结果的顺序
- javascript - Node.js - 如何使用 Promise 测试 HTTPS 请求
- android - 有没有办法创建一个“永久”文件?
- refactoring - 如何解决命令模式中命令处理器中方法过多的问题