可迭代对象与惰性求值
Coddy 面向 R 开发者的 Dart 课程 课程的第 18 课,共 48 课。
R 语言中的 lapply、sapply 和 Map 是急切求值的:它们会对每个元素调用函数并返回完成的结果。R 的参数 promise 提供了另一种惰性机制,但它们不会让这些集合操作变成惰性的。Dart 的 map 会返回一个惰性的 Iterable,它会在被遍历时运行回调函数,并且可以再次被遍历并重新运行回调。当需要稳定的求值结果时,可以使用 toList 将其具体化为列表。
Dart 的 map 和 where 会返回惰性的 Iterable。回调函数会在请求元素时运行,后续的遍历可以重复运行它。当需要具体的快照时,toList 会将结果具体化。
完整的 R 程序:
twice <- function(n) {
cat(sprintf("visit:%d\n", n))
n * 2L
}
result <- lapply(c(2L, 3L), twice)
cat("made\n")
cat(result[[1]], "\n", sep = "")
完整的 Dart 程序:
void main(){final result=[2,3].map((n){print('visit:$n');return n*2;});print('made');print(result.first);}挑战
简单实现 excess(List<int> values,int floor):筛选出严格大于 floor 的值,减去 floor,保持原有顺序,并返回一个新列表。输入为 floor 以及随后的 values,数值范围均为 -100 到 100。输出用逗号分隔的结果,或 empty。
请勿在可编辑文件中进行打印。提供的 exercise.dart 解析输入并返回输出;被锁定的驱动程序会独立测试公共 API,并打印带有单行换行符的结果。
你的代码写在 functions.dart、exercise.dart 中。main.dart 包含提供的输入/输出代码,无法编辑。
亲手试试
import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'functions.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
check(excess([3,7,4],3).join(',')=='4,1');
stdout.writeln(solve(input));
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 R 开发者的 Dart 课程中的所有课
自己练习: Dart 在线编译器