我们实现的方式是根据 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}]
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}]