【问题标题】:How to rewrite a for-loop Seq output into Stream output?如何将 for-loop Seq 输出重写为 Stream 输出?
【发布时间】:2013-04-04 10:59:06
【问题描述】:

我尝试将此 Scala 函数转换为返回惰性流,而不是急切地检索所有结果,并在所有结果都存在时将它们从 Seq 转换为 Stream。我觉得问题在于 (for (i 。

感谢任何建议。我正在寻找的另一个解决方案是在找到结果时返回结果。使用此解决方案,我可能只返回 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
  }

【问题讨论】:

    标签: scala stream


    【解决方案1】:

    for (i &lt;- 1 to 9; z &lt;- solve(???)) yield z 表示(1 to 9).flatMap{i =&gt; solve(???)}。见this answer

    要生成惰性结果,您应该使用 (1 to 9).view(1 to 9).toStream 使源 (1 to 9) 变得惰性。

    试试这个:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-03
      • 1970-01-01
      • 1970-01-01
      • 2019-03-11
      • 2014-11-25
      • 1970-01-01
      相关资源
      最近更新 更多