在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当然,它可以通过命令式的方式直接转换成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)
}
}但我想以适当的、函数式的方式来做。
我假设在某种2D范围内应该有map操作。理想情况下,map将执行一个函数,该函数将x和y作为输入参数并输出Option[Item]。在那之后,我会得到像Iterable[Option[Item]]和flatten这样的东西,它会产生Iterable[Item]。如果我是对的,那么拼图中唯一缺少的部分就是以某种方式在2D范围上执行映射操作。
发布于 2012-12-14 01:53:12
您可以在一个很好的步骤中完成所有这些操作:
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现在假设我们在一个四乘四的黑板上有这样的符号表示:
val tileMap = Map(
(0, 0) -> 'a,
(1, 0) -> 'b,
(3, 2) -> 'c
)我们只需要写:
scala> items(4, 4)(tileMap.get)
res0: IndexedSeq[Symbol] = Vector('a, 'b, 'c)我想这就是你想要的。
https://stackoverflow.com/questions/13865344
复制相似问题