我试图将此Scala函数转换为返回惰性流,而不是急切地检索所有结果,并在所有结果都存在时将它们从Seq转换为Stream.我感觉问题在于(for(i < - 1到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
}
Run Code Online (Sandbox Code Playgroud)
sen*_*nia 11
for (i <- 1 to 9; z <- solve(???)) yield z手段(1 to 9).flatMap{i => solve(???)}.看到这个答案.
要生成延迟结果,您应该1 to 9使用(1 to 9).view或使source()延迟(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
Run Code Online (Sandbox Code Playgroud)