Scala makeString + pre + sep + post with foldLeft

Viewed 17

so I would like to create a string like "[a-to-b]" def my func

def makeString(xs: List[String], pre : String, sep: String, post: String) : String =xs match{
case Nil => ""
case head::tail =>  xs.foldLeft(pre)((r,e) => r + sep + e) + post }

scala > makeString(List("a","to","b"), "[","-","]")

but it turned outString = [a-to-b-]

How can I fix it? Thanks

1 Answers

You've already extracted head and tail, you might as well use them for your foldLeft (instead of pre and xs) and put pre and post outside it.

def makeString(xs: List[String], pre : String, sep: String, post: String): String =
  xs match {
    case Nil => ""
    case head::tail =>  pre + tail.foldLeft(head)((r,e) => r + sep + e) + post
  }

Example Scastie

Related