Jus12
Jus12

Reputation: 18034

An alternate to foldLeft that starts from second element

I have a List defined as:

val l = List("1", "2", "3")

I want to convert it to the string

"1:2:3"

One way is the following:

l.foldLeft("")((x, y) => x + (if (x == "") "" else ":") +y)

Is there a more elegant method?

[EDIT: further explanation]

Easy Angel's answer works when the elements of l have a 'meaningful' toString method.

although I have l as List[String], l can be a list of a custom type which does not override the toString method, say, as in:

class my(i:Int) {
  val x = i
}

I have also a method

def getMy(m:my) = "Hello "+m.x

So I would like the output of getMy to be used instead of the output of the default toString method.

Upvotes: 3

Views: 1134

Answers (3)

tenshi
tenshi

Reputation: 26586

You can use mkString method of List:

l mkString ":"

More info can be found in scaladoc:

http://www.scala-lang.org/api/rc/scala/collection/Iterable.html#mkString:String


As alternative you can use reduceLeft for example:

l.reduceLeft(_ + ":" + _)

As an answer to your second question: Just combine it with map:

l map getMy mkString ":"

Upvotes: 9

Landei
Landei

Reputation: 54584

The other suggestions are better, but when you want to keep foldLeft, you could use Options:

List("1","2","3").foldLeft(None:Option[String])((o,n)=> o.map(_+":"+n).orElse(Some(n))).get
//res2: String = 1:2:3

Upvotes: 1

driushkin
driushkin

Reputation: 3659

another way to do this with just foldLeft:

l.tail.foldLeft(l.head)( (x, y) => x+":"+y )

Upvotes: 2

Related Questions