在 DAML 中,如何查找和替换列表中的元素

In DAML, how to find and replace an element in a List

如果我有一个数据列表 [Item],查找和更改其中元素的最佳方法是什么。

aList : [Item]
searchName : Text
newPrice : Decimal


- I can find the element using 
let a : Optional Int = findIndex (\a -> a.name == searchName) aList

-but this doesn't change the value of the List
let (aList !! fromSome a).price = newPrice

data Item = Item 
  with
    name : Text
    price : Decimal
  deriving (Eq, Show)

DAML 中的值是 不可变的 - 这意味着一旦您创建了一个列表,就无法更新其中的任何值。然而,有许多辅助函数可用于创建新列表,与旧列表非常相似,但有一些变化。例如:

let newList = map (\a -> if a.name == searchName then a{price = newPrice} else a) aList

map 函数获取列表中的每个元素并应用给定的函数。我们传递的函数更改 price 那些具有正确名称的函数,并且 returns 所有其他不变。请注意,与您的版本不同,这会更改所有带有 searchName 的项目,而不仅仅是第一个 - 我假设这很好(但如果不是,请先使用 partition 之类的函数来划分列表)。