Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala List match last element

I'm currently learning Scala and I'm amazed. The language handles so much problems quite elegant. But, I got a problem when it comes to matching the last element of a list.

Let's have 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 quite 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 that?

like image 837
bash0r Avatar asked Mar 18 '23 19:03

bash0r


2 Answers

You need to switch the order. The xs symbol will eagerly match anything in that position. Trying to match Nil first will make that statement no longer unreachable. Also, you'll still need to match Nil by itself to account for empty lists.

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

Though mkString already does what you're looking to make.

like image 92
Michael Zajac Avatar answered Mar 31 '23 07:03

Michael Zajac


Here's an implementation using List#foldRight:

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

When folding over this list, we need to check for when the accumulator is empty. Otherwise, we'll get an extra : at the end of the stringfied string result.

Tests

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

scala> stringify(List("1", "2" , "3", "500") )
res7: String = 1:2:3:500
like image 45
Kevin Meredith Avatar answered Mar 31 '23 06:03

Kevin Meredith