bash0r
bash0r

Reputation: 804

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?

Upvotes: 4

Views: 3275

Answers (2)

Kevin Meredith
Kevin Meredith

Reputation: 41909

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

Upvotes: 1

Michael Zajac
Michael Zajac

Reputation: 55569

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.

Upvotes: 6

Related Questions