Better one liner to generate n spaces

Yes, this is a funny question, but I want to learn how to use collection operations such as map, shrink and collapse correctly.

I did this:

scala> Range(0,3) map(_=>" ") reduceLeft(_+_)
res15: java.lang.String = "   "

      

What's the best idiomatic way to generate n spaces with a collection operation?

+3


source to share


4 answers


Technically the next "collection operation" I think is because it StringOps

is in the package scala.collection.immutable

:

scala> " " * 3
res1: String = "   "

      

What's going on here is what is " "

implicitly converted to an instance StringOps

using scala.Predef.augmentString

and then *

to StringOps

.




Update: I meant this kind of as a joke of sorts, since this is clearly not what you mean by "collect operation" - it is not a higher order function like map

or reduce

. I would definitely use my version (version StringOps

) in real code, but if you want to use higher order functions (for educational reasons, for a similar problem, etc.), I think your version is pretty close to idiomatic. I personally used until

to plot a range and reduce

instead of reduceLeft

(since concatenation is associative) -ie, pretty much what virtualeyes wrote in his or her answer.

+15


source


Not as elegant as Travis's solution, but imho the second most elegant way is:



List.fill (3)(' ').mkString 

      

+4


source


1 until 10 map (_=> " ") reduce(_+_)

      

- another, possibly more readable approach

+2


source


I think it is foldLeft

more correct:

Range(0,3).foldLeft("")((str, i) => str + " ")

      

+1


source







All Articles