scala - Merging a list of Strings using mkString vs foldRight -
i trying out things in scala, trying accustomed functional programming leaning new language again (it's been while since last time).
now given list of strings if want merge them 1 long string (e.g. "scala", "is", "fun" => "scalaisfun"
) figured 1 way foldright
, apply concatenation on respective elements. way, admittedly simpler, call mkstring
.
i checked on github couldn't find source code respective functions (any on appreciated), not sure how functions implemented. top of head, think mkstring
more flexible feels there might foldright
in implementation somewhere. there truth it?
otherwise scaladocs mention mkstring
calls on tostring
each respective element. seeing strings start with, 1 negative point mkstring
in particular case. comments on pros , cons of both methods, respect performance, simplicity/elegance etc?
simple answer: use mkstring
.
somestring.tostring
returns same object.
mkstring
implemented single stringbuilder
, creates 1 new string. foldleft
you'll create n-1
new strings.
you use stringbuilder
in foldleft
, fast mkstring
, mkstring
shorter:
strings.foldleft(new stringbuilder){ (sb, s) => sb append s }.tostring strings.mkstring // same result, @ least same speed
Comments
Post a Comment