Question: I have recently started learning functional programming on a SCALA. I used the recursive function to print elements of the list, now I would like to print elements starting from the end `("Ann" ...)` but also using recursive function, can anyone please help me to transform the code?

```
object Scala {
  val names: List[String] = List("Adam", "Mick", "Ann");
  def main(args: Array[String]) {
    println(printNames(names))
    def (printNames (name: List[String] ) {
      if(names.isEmpty) ""
      else  names.head + (printNames(names.tail);
    }
  }
}

```

Answer: 
You can use the following definition:

```
def printNames(names: List[String]): String = {
  if(names.isEmpty) ""
  else printNames(names.tail) + " " + names.head
}

```

Note that this implementation is not tail recursive and cannot be optimized by scala compiler. I strongly advise using an accumulator for the resulting `String`.

Luis Miguel Mejía Suárez suggests using `StringBuilder` to avoid expensive `String` concatenation:

```
def printNames(names: List[String]): StringBuilder = {
  if(names.isEmpty) new StringBuilder("")
  else printNames(names.tail).append(" ").append(names.head)
}

```
```
def printNames(names: List[String]): String = names.reverse.mkString(" ")

```

You can reverse the name list and then use mkString with space as a separator. The above one can be used to achieve the same without recursion, as mkString by default uses StringBuilder.

As you were looking for a tail-recursive solution

```
import scala.annotation.tailrec

def printNames(names: List[String]): String = {
  @tailrec
  def printNamesHelper(
      names: List[String],
      acc: StringBuilder = new StringBuilder("")
  ): String = {
    names match {
      case Nil          => acc.toString.trim
      case head :: tail => printNamesHelper(tail, acc.append(head).append(" "))
    }
  }
  printNamesHelper(names)
}

def printNamesReverse(names: List[String]): String = {
  @tailrec
  def printNamesReverseHelper(
      names: List[String],
      accum: List[String] = List.empty
  ): String = {
    names match {
      case Nil          => printNames(accum)
      case head :: tail => printNamesReverseHelper(tail, head :: accum)
    }
  }
  printNamesReverseHelper(names)
}

printNames(List("Adam", "Framk"))
printNamesReverse(List("Adam", "Framk"))

```

Added scastie snippet below:

```html
<script src="https://scastie.scala-lang.org/shankarshastri/0dxWt7K3S8CkkAffliLICQ/7.js"></script>
```