fishb6nes
fishb6nes

Reputation: 125

Scala LazyList of finite range

I've been trying to create a LazyList of a series of items, blocks in this case, which have to be accessed in a 3-dimensional array like fashion.

  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)
  }

The generation of the list has turned out rather clean, but I feel there has to be a better way to take care of incrementing the x, y, and z values in the same order as they would in 3 nested for loops (where min.x <= x <= max.x, etc).

Is there a page that can be taken from for loop comprehension or ranges that is usable when working with LazyLists?

Something like

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

Upvotes: 2

Views: 909

Answers (1)

jwvh
jwvh

Reputation: 51271

Something like this?

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>)

Actually you only need to make the x generator a LazyList. The result type will follow.

Upvotes: 6

Related Questions