gpt4 book ai didi

functional-programming - Dart 中的产量示例

转载 作者:行者123 更新时间:2023-12-04 20:05:06 26 4
gpt4 key购买 nike

如何在 Dart 中像 Scala 一样使用 yield?Scala 中有一个例子“https://alvinalexander.com/scala/scala-for-loop-yield-examples-yield-tutorial

scala> val a = Array(1, 2, 3, 4, 5)
a: Array[Int] = Array(1, 2, 3, 4, 5)

scala> for (e <- a if e > 2) yield e
res1: Array[Int] = Array(3, 4, 5)

我怎样才能在 Dart 中做到这一点?

void main() {
var a = [1, 2, 3, 4, 5];

for (var e in a) {
if (e > 2) yield e;
}
}

最佳答案

Dart 和 JavaScript 具有异步/等待机制。

异步产生值的函数是一个返回 Stream 的异步函数

Stream<int> str() async* {
// The keyword `async*` means a "generator function" that generates a stream
List<int> a = [1, 2, 3, 4, 5];
for (var e in a) {
if (e > 2) yield e;
}
}

main() async {
await for (var e in str()) {
print(e);
}
}

关于functional-programming - Dart 中的产量示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52793394/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com