我试图将这个 Scala 函数转换为返回一个惰性流,而不是急切地检索所有结果,并在所有结果都存在时将它们从 Seq 转换为 Stream。我感觉问题出在 (for (i <- 1 to 9; z <- solve(xs.updated(pos, i), pos)) yield z) toStream .
任何建议表示赞赏。我正在寻找的另一个解决方案是在找到结果时返回结果。使用此解决方案,我可能只返回 1 个结果。谢谢isConflictAt(xs.updated(pos, 0), pos, xs(pos)
是一个约束检查函数。
def solve(xs : List[Int], pos: Int): Stream[List[Int]] = {
if (!isConflictAt(xs.updated(pos, 0), pos, xs(pos))) {
val pos = xs.indexOf(0)
if (pos < 0) {println(xs); Stream(xs) } else (for (i <- 1 to 9; z <- solve(xs.updated(pos, i), pos)) yield z) toStream
} else Stream.empty
}
最佳答案
for (i <- 1 to 9; z <- solve(???)) yield z
意味着 (1 to 9).flatMap{i => solve(???)}
.见 this answer .
要生成惰性结果,您应该使用 1 to 9
使源( (1 to 9).view
)变得惰性或 (1 to 9).toStream
.
尝试这个:
scala> def solve(pos: Int): Stream[List[Int]] = {
| println(pos)
| Stream.fill(3)((1 to pos).map{ _ => util.Random.nextInt}.toList)
| }
solve: (pos: Int)Stream[List[Int]]
scala> for{
| i <- (1 to 9).toStream
| z <- solve(i)
| } yield z
1
res1: scala.collection.immutable.Stream[List[Int]] = Stream(List(-1400889479), ?)
scala> res1.force
2
3
4
5
6
7
8
9
关于scala - 如何将 for 循环 Seq 输出重写为 Stream 输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15809253/