Scala - List from the end (problem with commas)

Viewed 76

I have to print list elements from the end with commas in between and no comma at the end. Code:

val daysList = List("Poniedzialek", "Wtorek", "Sroda", "Czwartek", "Piatek", "Sobota", "Niedziela")

 def recurencyListReverse(days:List[String], twoB:String):String =
  {
    if (days.nonEmpty) return recurencyListReverse(days.tail, days.head + ", " + twoB)
    return twoB
  }
  println("Zadanie 2B)")
  println(recurencyListReverse(daysList, ""))

Any ideas?

2 Answers

Basic recursion.

def recurencyListReverse(days:List[String]):String = days match {
  case day :: Nil => day
  case day :: tail => recurencyListReverse(tail) + s", $day"
  case _ => ""
}

If you want it tail-recursive.

def recurencyListReverse(days:List[String]):String = {
  @annotation.tailrec
  def loop(ds: List[String], connect:String, acc:String):String =
    if (ds.isEmpty) acc
    else loop(ds.tail, ", ", ds.head + connect + acc)
  loop(days, "", "")
}

If you only need it for "printing," mkString() should suffice.

scala> daysList.mkString(", ")
res1: String = Poniedzialek, Wtorek, Sroda, Czwartek, Piatek, Sobota, Niedziela

scala> daysList.reverse.mkString(", ")
res2: String = Niedziela, Sobota, Piatek, Czwartek, Sroda, Wtorek, Poniedzialek
Related