Thi*_*ult 5 arrays indexing list elm
我刚刚开始在Elm编程并且遇到了困难:
我想有一个方法可以更新某个索引列表中的元素字段.
我的签名看起来像这样:
updateElement : List (ID, Task) -> Int -> List (ID, Task)
Run Code Online (Sandbox Code Playgroud)
有:
type alias Task =
{ description : String, focus : Bool}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我想将任务的布尔(焦点)设置为给定为true的索引,将列表中的所有其他任务设置为false.
我已经尝试过使用Elm中的数组,但后来我必须使用Maybe,并且不认为这是一个很好的解决方案.
我想我将不得不使用'map'来更改列表中的元素,但我不知道如何在特定索引处更改它.
谢谢!
现在您已经澄清了您的问题,真正的答案是Chad发布的两个更新的组合
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
Run Code Online (Sandbox Code Playgroud)
如果您只想经常更改列表的第 n 个元素,则 aList将是错误的数据结构。Listelm 中的A被实现为一个链表,它在随机访问的性能方面表现不佳。
对于这种工作,您可能更应该使用 elm Array,实际上 Array 确实有一个简单的函数来设置第 n 个元素,而其他所有元素保持不变:Array.set :: Int -> a -> Array a - > 数组 a。
在该主题上,有关 elm 错误跟踪器的讨论可能会引起人们的兴趣。
| 归档时间: |
|
| 查看次数: |
4528 次 |
| 最近记录: |