1

I have a list of strings, like

val myList = List("apple", "orange", "pear")

I would like to transform it to a string like "1) apple 2) orange 3) pear". I could write a for loop, but I think that in Scala there should be an one-liner for things like this. The best one-liner I could come up with was

val myString = myList.map(s => "1) " + s).mkString(" ")

But this results in "1) apple 1) orange 1) pear". How can increment a value while mapping a list?

WannaKnow
  • 1,155
  • 2
  • 11
  • 18
  • 1
    This is helpful: http://stackoverflow.com/questions/2213323/how-can-i-use-map-and-receive-an-index-as-well-in-scala – pt2121 Jun 06 '13 at 18:19

4 Answers4

8

Easy peasy (scala 2.10 with string interpolation):

myList.zipWithIndex.map { case (cases, i) => s"${i + 1}) $cases" }
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
2

I honestly wouldn't recommend it, but you can actually get your version working:

val myString = myList.map{var i=0; s => i+=1; i + ") " + s}.mkString(" ")
Landei
  • 54,104
  • 13
  • 100
  • 195
1

Actually, there is no missing plus sign. Try it. My minor modification is to add mkString at the end.

myList.zipWithIndex.map { case (cases, i) => s"${i + 1}) $cases" }.mkString(" ")
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
egprentice
  • 814
  • 7
  • 15
  • 1
    Well, there [was](http://stackoverflow.com/revisions/16969249/1) missing plus sign :-) – om-nom-nom Jun 06 '13 at 18:29
  • A small improvement suggestion, add `view` before zipWithIndex `myList.view.zipWithIndex.map { case (cases, i) => s"${i + 1}) $cases" }.mkString(" ")` so that the intermidiate list will be init in a lazy way – Max Jun 07 '13 at 01:34
0

My Solution is:

myList.map{value => s"${myList.indexOf(value)+1}) $value"}
User2403
  • 173
  • 1
  • 4
  • 15