榆树 - 更新列表中的元素 [英] Elm - update elements in a list
问题描述
我刚开始在Elm编程并且遇到了困难:
I just started programming in Elm and am stuck at something:
我想有一个方法可以在某个索引处更新列表中元素的字段。
I would like to have a method that can update fields of elements in a list at a certain index.
我的签名如下所示:
updateElement : List (ID, Task) -> Int -> List (ID, Task)
包含:
type alias Task =
{ description : String, focus : Bool}
在这种情况下,我想将给定为true的索引的任务的布尔(焦点)和列表中的所有其他任务设置为false。
In this case I would like to set the boolean (focus) of the task at the index given to true and all the others tasks in the list to false.
我已经尝试过使用Elm中的数组但是我必须使用Maybe并且不认为这是一个很好的解决方案。
I already tried with arrays in Elm but then I have to work with Maybe and don't think that is a good solution.
我想我会必须使用'map'来更改列表中的元素,但我不知道如何在特定索引处更改它。
I suppose I will have to work with 'map' to change elements in my list but I don't have any clue how I could change it at a particular index.
谢谢!
推荐答案
现在您已经澄清了您的问题,真正的答案是Chad发布的两个更新的组合
Now that you've clarified your question, the real answer is a combination of the two updates Chad posted
updateElement : List (ID, Task) -> Int -> List (ID, Task)
updateElement list indexToFocusOn =
let
toggle index (id, task) =
if index == indexToFocusOn then
(id, { task | focus = true })
else
(id, { task | focus = false })
in
List.indexedMap toggle list
这篇关于榆树 - 更新列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!