Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala最佳实践:映射二维数据_Scala_Functional Programming_Scala Collections - Fatal编程技术网

Scala最佳实践:映射二维数据

Scala最佳实践:映射二维数据,scala,functional-programming,scala-collections,Scala,Functional Programming,Scala Collections,在Scala中,以适当的函数方式在Java中执行以下代码的最佳方法是什么 LinkedList<Item> itemsInRange = new LinkedList<Item>(); for (int y = 0; y < height(); y++) { for (int x = 0; x < width(); x++) { Item it = myMap.getItemAt(cy + y, cx + x); if

在Scala中,以适当的函数方式在Java中执行以下代码的最佳方法是什么

LinkedList<Item> itemsInRange = new LinkedList<Item>();
for (int y = 0; y < height(); y++) {
    for (int x = 0; x < width(); x++) {
        Item it = myMap.getItemAt(cy + y, cx + x);
        if (it != null)
            itemsInRange.add(it);
    }
}

// iterate over itemsInRange later
LinkedList ItemsRange=new LinkedList();
对于(int y=0;y
当然,它可以以命令式的方式直接转换为Scala:

val itemsInRange = new ListBuffer[Item]
for (y <- 0 until height) {
    for (x <- 0 until width) {
        val it = tileMap.getItemAt(cy + x, cx + x)
        if (!it.isEmpty)
            itemsInRange.append(it.get)
    }
}
val itemsInRange=new ListBuffer[Item]

对于(y,您可以在一个很好的步骤中完成这一切:

def items[A](w: Int, h: Int)(at: ((Int, Int)) => Option[A]): IndexedSeq[A] =
  for {
    x <- 0 until w
    y <- 0 until h
    i <- at(x, y)
  } yield i
我们只是写:

scala> items(4, 4)(tileMap.get)
res0: IndexedSeq[Symbol] = Vector('a, 'b, 'c)

我想这正是你想要的。

谢谢!看起来这正是我想要的!这些
产量
的东西看起来很有前途!
scala> items(4, 4)(tileMap.get)
res0: IndexedSeq[Symbol] = Vector('a, 'b, 'c)