/// 集合:`List` / `Set` / `Map` 与它们的惯用法。 /// /// 关键差异(Go 程序员最容易忽略的一条): /// **Dart 的 Map / Set 默认保持插入顺序**(LinkedHashMap / LinkedHashSet), /// 而 Go 的 map 遍历顺序是随机的,C 里更没有"有序字典"这回事。 library; /// `map` / `where` / `fold` 是链式的高阶函数,比手写循环短,但注意每步都会新建集合。 List squaresOfEven(List xs) => xs.where((int x) => x.isEven).map((int x) => x * x).toList(); /// 分组:`Map>` 是 Dart 里的标准做法(Go 里是 `map[K][]V`)。 Map> groupByLength(List words) { final result = >{}; for (final w in words) { // `putIfAbsent` / `??=` 都能避免手写"先判断 key 是否存在"。 (result[w.length] ??= []).add(w); } return result; } /// 词频统计:`??=` 是 null-aware assignment,等价于 `if (m[k] == null) m[k] = 0`。 Map wordCounts(String text) { final counts = {}; for (final raw in text.toLowerCase().split(RegExp(r'\s+'))) { final word = raw.replaceAll(RegExp(r'[^a-z0-9]'), ''); if (word.isEmpty) continue; counts[word] = (counts[word] ?? 0) + 1; } return counts; } /// `Set` 去重;Dart 的 Set 用 `hashCode` + `==` 判重,与 C++ 的 unordered_set 同理。 Set uniqueWords(String text) => text.toLowerCase().split(RegExp(r'[^a-z]+')).where((String w) => w.isNotEmpty).toSet(); /// 排序:`sort` 是**原地**修改(像 Go 的 `sort.Ints`), /// 所以要保留原序必须先 `[...]` 复制(Go 里是 `slices.Clone`)。 List sortedDescending(List xs) => [...xs]..sort((int a, int b) => b.compareTo(a)); /// 固定长度列表:初始化后不能增删,但能改元素——像 C 的 `int arr[3]`。 List fixedSlots() => List.filled(3, 0); /// 生成序列:等价 Go 的 `for i := 0; i < n; i++ { append(...) }`。 List range(int n) => List.generate(n, (int i) => i); /// 不可变视图:对它的任何写操作抛 `UnsupportedError`(C 的 `const` 数组 / Go 没有对应物)。 List readOnlyTags() => List.unmodifiable(['dart', 'flutter']); /// 集合推导(collection-for / collection-if / spread):Dart 独有的紧凑写法。 List buildTags({ bool starred = false, List extra = const [], List? more, }) => [ 'dart', if (starred) 'starred', // collection-if for (final e in extra) 'extra:$e', // collection-for ...?more, // spread 可空集合:...? 遇到 null 直接跳过 ]; /// 嵌套集合:`Map>` 在配置文件里很常见。 Map> inventory() => { 'fruits': {'apple': 3, 'pear': 5}, 'tools': {'hammer': 1}, };