Scala最佳实践:映射二维数据
在Scala中,以适当的函数方式在Java中执行以下代码的最佳方法是什么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
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)