8

我试图将这个 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
  }
4

1 回答 1

11

for (i <- 1 to 9; z <- solve(???)) yield z意味着(1 to 9).flatMap{i => solve(???)}。看到这个答案

1 to 9要生成惰性结果,您应该使用(1 to 9).viewor使源 ( ) 变得惰性(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
于 2013-04-04T11:21:24.477 回答