arrays - Elm - 更新列表中的元素

标签 arrays list indexing elm

我刚开始在 Elm 中编程,但遇到了一些问题:

我想有一种方法可以更新列表中某个索引处的元素字段。

我的 签名看起来像这样:

updateElement : List (ID, Task) -> Int -> List (ID, Task)

和:
type alias Task =
  { description : String, focus : Bool}

在这种情况下,我想将索引处任务的 bool 值(焦点)设置为 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

关于arrays - Elm - 更新列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34502706/

相关文章:

html - 在您的根目录中有一个索引页面是否至关重要,例如 index.html、index.php

c++ - cout 指向数组项的指针打印出的值与预期不同

javascript - 我想删除没有特定数组的对象

java - 查找未排序集合的不同元素的最大值/最小值

java.util.List<T> t 代表什么?

java - 如何同步 Solr 导入过程?

java - 按钮的文本循环遍历字符串数组

c++ - std::string(char* char_array) 是如何实现的?

python - Python 中的重定向打印 : val = print(arg) to output mixed iterable to file

MySQL 为什么在此查询中 Distinct 关键字在自然语言模式下不起作用?