Scala: reduceLeft with String -


i have list of integers , want make string of it.

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

with foldleft works perfect, question work reduceleft? , if yes, how?

it cannot work way reduceleft. informally can view reduceleft special case of foldleft accumulated value of same type collection's elements. because in case element type int , accumulated value string, there no way use reduceleft in way used foldleft.

however in specific case can convert int elements string front, , reduce:

scala> xs.map(_.tostring) reduceleft(_+_) res5: string = 12345 

note throw exception if list empty. difference foldleft, handles empty case fine (because has explicit starting value). less efficient because create whole new collection (of strings) reduce on spot. in all, foldleft better choice here.


Comments

Popular posts from this blog

How to provide Authorization & Authentication using Asp.net, C#? -

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

How to use Authorization & Authentication in Asp.net, C#? -