Buddhi
Buddhi

Reputation: 89

Creating white space in a List in Scala

I am trying to convert a List of string to the form "rBrrBB", or "r r rb", or " rrB". The string must have length 6. If the this list is not full, then the list should be prefixed with an appropriate number of spaces

So far my code as below

def showColumn(xs: List[String]): String = xs match
{case List() => "" case x::xs1 => x.format(" ") + showColumn(xs1)}

when I call this from

println (showColumn(List("","","b","b","r","b")))

it returns only "bbrb". It suppose to return " bbrb" Any help would appreciate.

Upvotes: 0

Views: 449

Answers (1)

Mike Allen
Mike Allen

Reputation: 8249

Try this:

def showColumn(xs: List[String]): String = xs.map(x => if(x == "") " " else x).mkString

or, alternatively:

def showColumn(xs: List[String]): String = xs.map(x => if(x.isEmpty) " " else x).mkString

Both work by changing empty strings in the list to spaces, then merging each string in the list into a single string.

If you absolutely must make this a recursive function, then a solution which is not tail-recursive would look like this:

def showColumn(xs: List[String]): String = xs match {
  case Nil => ""
  case x :: xs1 => (if(x.isEmpty) " " else x) + showColumn(xs1)
}

Finally, the tail-recursive version is a little more complex, as it employs a helper function:

import scala.annotation.tailrec

def showColumn(xs: List[String]): String = {

  // Tail recursive helper function.
  @tailrec
  def nextStr(rem: List[String], acc: String): String = rem match {
    case Nil => acc
    case x :: xs1 => nextStr(xs1, acc + (if(x.isEmpty) " " else x))
  }

  // Start things off.
  nextStr(xs, "")
}

Upvotes: 3

Related Questions