scala - 如何将 for 循环 Seq 输出重写为 Stream 输出?

标签 scala stream

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

相关文章:

java - NoSuchBeanDefinitionException : No qualifying bean of type 'java.util.List<org.springframework.shell.ParameterResolver>'

java - 将两个 scala.collection.Iterable 隐藏到 Java List 或 Iterator 中

java - 使用 YASEA 串流 key

c - 编码(marshal)处理/解封处理与序列化/反序列化之间有什么区别?

python - 如何在 python 3.4 中预处理 yaml 文件?

scala - _::在 Scala 中是什么意思?

scala - 本地 Actor 和远程 Actor 之间的行为不一致

c# - 为什么 StreamReader 返回字符串而不是字节数组

scala - 在 Circleci 上运行测试时获取文件名太长

node.js - 使用管道语法解压缩流响应