Use an array as a Scala foldLeft drive

I am trying to use foldLeft for an array. For instance:

var x = some array x.foldLeft(new Array[Int](10))((a, c) => a(c) = a(c)+1) 

This does not allow the required array [Int] to be compiled with the Int (0) error found.

+6
source share
2 answers

To use foldLeft in what you want to do, and following your style, you can simply return the same drive array in the calculation, 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)) 
+5
source

An assignment in Scala does not return a value (but instead a Unit), so your expression, which should return Array [Int] for the next step, returns a Unit that does not work.

You will need to use the block and return the array at the end like this:

 x.foldLeft(new Array[Int](10)) { (a, c) => a(c) = a(c)+1 a } 
+2
source

Source: https://habr.com/ru/post/983285/


All Articles