Scala:折叠二维数组

her*_*man 2 functional-programming scala

给定一个潜在的大图像(或二维数字数组),我想循环所有像素(或数字),例如计算所有黑色(或0值).

我知道我可以简单地使用一个理解

for (y <- 0 until img.height; x <- 0 until img.width) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

但是我需要一个可变的变量来计算.这可能不是一个真正的问题,但假设我不想要这个并且想要使用更多功能的样式,如何在不创建宽度为x高度元素的大型数据结构的情况下执行此操作(换句话说,保留内存 - 效率0 until img.height0 until img.width范围)?

Mar*_*rth 5

映射集合,将内部转换为子容器,然后对它们求和:

scala> val m = Array(
         Array("B","B","W"),
         Array("W","W","B"),
         Array("W","W","W")
       )
m: Array[Array[String]] = Array(Array(B, B, W), Array(W, W, B), Array(W, W, W))

scala> m.map(_.count(_ == "B")).sum
res0: Int = 3
Run Code Online (Sandbox Code Playgroud)

编辑

您可以创建一个Stream使用

Stream.tabulate(img.height, img.width)(identity)
Run Code Online (Sandbox Code Playgroud)

然后使用

stream.count(isBlack)
Run Code Online (Sandbox Code Playgroud)

请注意,Stream.tabulate最多接受5个维度(作为其第一个参数).

  • @SarveshKumarSingh在Scala中它起作用. (5认同)