I am trying to use a foldLeft on an array. Eg:
var x = some array
x.foldLeft(new Array[Int](10))((a, c) => a(c) = a(c)+1)
This refuses to compile with the error found Int(0) required Array[Int].
In order to use foldLeft
in what you want to do, and following your style, you can just return the same accumulator array in the computation like this:
val ret = a.foldLeft(new Array[Int](10)) {
(acc, c) => acc(c) += 1; acc
}
Alternatively, since your numbers are from 0 to 9, you can also do this to achieve the same result:
val ret = (0 to 9).map(x => a.count(_ == x))
Assignment in Scala does not return a value (but instead Unit) so your expression that is supposed to return the Array[Int] for the next step returns Unit which does not work.
You would have to use a block and return the array in the end like this:
x.foldLeft(new Array[Int](10)) { (a, c) =>
a(c) = a(c)+1
a
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With