我们实现的方式是根据 struct 推导将 list 转换为 “map”,然后再将其转回 list。
unique-list-by-key.cue
#elem: { key: string val: _}elems: [...#elem] & [ {key: "a", val: 1}, {key: "b", val: 1},// { key: "a", val: 2 }, // uncomment this line to see error {key: "b", val: 1},]set: [string]: #elemset: {for e in elems {"\(e.key)": e }}uniq: [ for s in set {s}]
cue eval unique-list-by-key.cue
根据 Value 去重
这里要实现的是基于所有的 Value 检测并移除重复数据。
我们使用了 list 包还有 list 推导。
unique-list-by-val.cue
import"list"#elem: { key: string val: _}elems: [...#elem] & [ {key: "a", val: 1}, {key: "b", val: 1}, {key: "a", val: 2}, {key: "b", val: 1},]// we compare the current element and add it if it does not appear in the remainder of the list// in doing so, we add the last unique occurance to the resultuniq: [ for i, x in elems if!list.Contains(list.Drop(elems, i+1), x) {x}]