Scala: reduceLeft with string
I have a list of integers and I want to create it.
var xs = list(1,2,3,4,5)
(xs foldLeft "") (_+_) // String = 12345
with foldLeft it works fine, but my question is, does it work with reduceLeft as well? And if so, how?
It cannot work that way with reduceLeft
. Informally, you can view it reduceLeft
as a special case foldLeft
where the accumulated value is of the same type as the elements of the collection. Since in your case the type of the element Int
, and the accumulated value String
, cannot be used reduceLeft
in the way you used foldLeft
.
However, in this particular case, you can simply convert all elements Int
to the String
front and then shrink:
scala> xs.map(_.toString) reduceLeft(_+_)
res5: String = 12345
Note that this will throw an exception if the list is empty. This is another difference from foldLeft
, which handles the empty case just fine (since it has an explicit seed). It's also less efficient because we are creating a whole new collection (of strings) to shrink in place. In general, foldLeft
there is a much better choice here.
It takes a little work to make sure the types are understood correctly. Expanding them, you could use something like:
(xs reduceLeft ((a: Any, b: Int) => a + b.toString)).toString