【问题标题】:Scala LazyList of finite range有限范围的Scala LazyList
【发布时间】:2023-03-12 17:42:01
【问题描述】:

我一直在尝试创建一系列项目的 LazyList,在本例中为块,它们必须像时尚一样以 3 维数组进行访问。

  def getBlocks: LazyList[Block] = getBlocks(min.x, min.y, min.z)

  private def getBlocks(x: Int, y: Int, z: Int): LazyList[Block] = {
    val (nextX, nextY, nextZ) = {
      if (z == max.z) (x, y + 1, min.z)
      else if (y == max.y) (x + 1, min.y, min.z)
      else (x, y, z + 1)
    }

    if (y > max.y) LazyList.empty
    else worldService.getBlock(world, x, y, z) #:: getBlocks(nextX, nextY, nextZ)
  }

列表的生成结果相当干净,但我觉得必须有更好的方法来处理 x、y 和 z 值的递增顺序,就像它们在 3 个嵌套 for 循环中的顺序一样 (其中min.x <= x <= max.x 等)。

在使用 LazyLists 时,是否有可以从 for 循环理解或范围中获取的页面?

类似

for {
  x <- min.x to max.x
  y <- min.y to max.y
  z <- min.z to max.z
} yield (x, y, z)

【问题讨论】:

  • 也许LayzList.unfold 会有所帮助?

标签: scala


【解决方案1】:

这样的?

for {
  x <- LazyList.range(min.x, max.x+1)
  y <- LazyList.range(min.y, max.y+1)
  z <- LazyList.range(min.z, max.z+1)
} yield (x, y, z)
//res0: LazyList[(Int, Int, Int)] = LazyList(<not computed>)

其实你只需要把x生成器变成LazyList。结果类型将随之而来。

【讨论】:

    猜你喜欢
    • 2021-12-20
    • 1970-01-01
    • 2020-07-20
    • 2020-05-24
    • 2023-03-15
    • 2015-11-24
    • 2013-10-21
    • 2016-11-19
    • 1970-01-01
    相关资源
    最近更新 更多