Home > Enterprise >  Ad hoc function in scala to concatenate two lists recursively: No use of "concat"
Ad hoc function in scala to concatenate two lists recursively: No use of "concat"

Time:10-20

I want to have a function in Scala that concatenate two lists without using the built-in functions of that purpose. It should be written in a functional recursive way but I am not sure where to start.

def concatList(lleft: List[String], lright: List[String]): List[String] {

  }

CodePudding user response:

Hopefully you solved your homework question by now. For anyone stumbling on this in the future, you can use tail recursion like this

def concatList(lleft: List[String], lright: List[String]): List[String] = lright match {
  case Nil => lleft  // base condition
  case head :: tail =>  // add first element to end of lleft and recurse
    concatList(lleft :  head, tail)
  case _ => lleft
}
  • Related