Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use an array as a Scala foldLeft accumulator

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].

like image 303
user1742188 Avatar asked Mar 03 '15 21:03

user1742188


2 Answers

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))
like image 111
ale64bit Avatar answered Oct 25 '22 02:10

ale64bit


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
}
like image 35
johanandren Avatar answered Oct 25 '22 01:10

johanandren