【问题标题】:Generating iterator instead of list in recursion在递归中生成迭代器而不是列表
【发布时间】:2016-04-28 23:45:21
【问题描述】:

a good question 表示我们应该流式传输/查看或迭代我们的集合以按需生成它们。很明显。我只是不明白我应该在下面的演示中应用.view.iterate 什么

val l1 = List("10", "00", "0")
def gen(depth: Int): Iterable[String] = if (depth == 1) l1 else {
    for (sub <- gen(depth-1); item <- List(depth + sub, sub+sub, sub)) yield item
} 

我应该将它们应用于gen(depth-1) 还是List(depth+..)

顺便说一句,我应该在(depth == 1) l1 else 中内联l1 吗?它不在其他任何地方使用。我只是担心它会为每一片叶子创建一个新列表。

【问题讨论】:

    标签: scala collections stream iteration ondemand


    【解决方案1】:

    我必须尝试一下,但我会说List(depth+..).view,因为你不会多次使用相同的值。我认为考虑到你在那里的递归,它会给你一种 DFS 遍历。

    是的,我不会内联它,而是像这样生活l1。我什至会做val l1 = List("10", "00", "0").view

    【讨论】:

      猜你喜欢
      • 2022-01-15
      • 1970-01-01
      • 2021-02-09
      • 2014-07-07
      • 2017-12-07
      • 2022-11-11
      • 2016-03-13
      • 2011-03-11
      • 2011-10-06
      相关资源
      最近更新 更多