Scala:折叠二维数组

Scala:折叠二维数组,scala,functional-programming,Scala,Functional Programming,给定一个可能较大的图像(或二维数字数组),我想循环所有像素(或数字),例如,计算所有黑色像素(或0值) 我知道我可以简单地用a来理解 for (y <- 0 until img.height; x <- 0 until img.width) { ... } for(y映射集合,将内部数转换为子数,然后求和: scala> val m = Array( Array("B","B","W"), Array("W","W","B"),

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

我知道我可以简单地用a来理解

for (y <- 0 until img.height; x <- 0 until img.width) {
    ...
}

for(y映射集合,将内部数转换为子数,然后求和:

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

编辑

您可以使用创建

Stream.tabulate(img.height, img.width)(identity)
然后使用

stream.count(isBlack)

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

您可以使用范围理解将图像转换为像素序列:

for {
    y <- 0 until img.height
    x <- 0 until img.width
} yield image(x, y)
用于{

y只是提醒您,
“abc”==“abc”
不起作用。图像不是集合。我添加了二维数组部分,因为我不需要关于如何使用的信息,例如,Scala中的BuffereImage,以及可以用来查找一对坐标的任何信息。因此,我想我需要从x和y范围开始的内容。此外,我更喜欢一个通用答案还有两个以上的维度,并且仍然是内存有效的。我认为我应该将范围转换为流,但不知道如何从那里开始。scala中的
==
相当于Java中的
.equals
。要获得引用等式,可以使用scala的
eq
操作符,如
if(“abc”eq“abc”)中的
+1教我制表。我想我应该使用一个函数来查找(Int,Int)的颜色,而不是
identity
,对吗?显然取决于您的应用程序,但是是的,
(Int,Int)=>color
(Int,Int)=>Pixel
似乎很合理。这似乎与我对streams的想法相似,但视图可能更好,因为我无论如何都想防止记忆。
for {
    y <- (0 until img.height).view
    x <- (0 until img.width).view
} yield image(x, y)
(
    for {
        y <- (0 until img.height).view 
        x <- (0 until img.width).view
    } yield image(x, y)
).count(_.isBlack)
implicit class ImageOperations(image: Image) {
    def toPixelSeq = for {
        y <- (0 until img.height).view 
        x <- (0 until img.width).view
    } yield image(x, y)
}