Scala List corresponds to the last item

I am currently studying Scala and am amazed. The language handles such problems quite elegantly. But I got a problem when it comes to matching the last element of the list.

Take a look at this code:

def stringify(list: List[String]): String = list match {
  case x :: xs => x + (if (xs.length != 0) ":" else "") + stringify(xs)
  case Nil => ""
}

This is rather inelegant, and I would like to write it more intuitive, something like this:

def stringify(list: List[String]): String = list match {
  case x :: xs => x + ":" + stringify(xs)
  case x :: Nil => x
}

How can i do this?

Thanks in advance!

+4
source share
2 answers

. xs - . Nil . , Nil .

def stringify(list: List[String]): String = list match {
   case x :: Nil => x
   case x :: xs => x + ":" + stringify(xs)  
   case Nil => ""
}

mkString , .

+5

List#foldRight:

 def stringify(list: List[String]): String = 
         list.foldRight(""){ 
               (e, acc) => if (acc.isEmpty) e 
                           else { e + ":" + acc } 
         }

, . : stringfied.

scala> stringify(List("1", "2" , "3") )
res6: String = 1:2:3

scala> stringify(List("1", "2" , "3", "500") )
res7: String = 1:2:3:500
+1

All Articles