0

如果我有一个数据列表 [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)
4

1 回答 1

2

DAML 中的值是不可变的——这意味着一旦您创建了一个列表,就无法更新其中的任何值。然而,有很多辅助函数可以用来创建一个新列表,就像旧列表一样,但有一些变化。举个例子:

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

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

于 2019-05-22T19:31:10.590 回答