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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With