Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: reduceLeft with String

Tags:

scala

I have a list of Integers and I want to make a String of it.

var xs = list(1,2,3,4,5)
(xs foldLeft "") (_+_)               // String = 12345

with foldLeft it works perfect, but my question is does it also work with reduceLeft? And if yes, how?

like image 565
Felix Junghans Avatar asked Dec 20 '22 02:12

Felix Junghans


2 Answers

It cannot work this way with reduceLeft. Informally you can view reduceLeft as a special case of foldLeft where the accumulated value is of the same type as the collection's elements. Because in your case the element type is Int and the accumulated value is String, there is no way to use reduceLeft in the way you used foldLeft.

However in this specific case you can simply convert all your Int elements to String up front, and then reduce:

scala> xs.map(_.toString) reduceLeft(_+_)
res5: String = 12345

Note that this will throw an exception if the list is empty. This is another difference with foldLeft, which handles the empty case just fine (because it has an explicit starting value). This is also less efficient because we create a whole new collection (of strings) just to reduce it on the spot. All in all, foldLeft is a much better choice here.

like image 83
Régis Jean-Gilles Avatar answered Dec 21 '22 14:12

Régis Jean-Gilles


It takes a little bit of work to make sure the types are understood correctly. Expanding them, though, you could use something like:

(xs reduceLeft ((a: Any, b: Int) => a + b.toString)).toString
like image 43
rjz Avatar answered Dec 21 '22 16:12

rjz