【问题标题】:Creating white space in a List in Scala在 Scala 的列表中创建空白
【发布时间】:2018-11-11 03:12:17
【问题描述】:
我正在尝试将字符串列表转换为“rBrrBB”、“r r rb”或“rrB”的形式。该字符串的长度必须为 6。如果此列表未满,则该列表应以适当数量的空格作为前缀
到目前为止我的代码如下
def showColumn(xs: List[String]): String = xs match
{案例列表()=>“”
案例 x::xs1 => x.format(" ") + showColumn(xs1)}
当我从
调用它时
println(showColumn(List("","","b","b","r","b")))
它只返回“bbrb”。它应该返回“bbrb”
任何帮助将不胜感激。
【问题讨论】:
标签:
scala
list
lambda
functional-programming
【解决方案1】:
试试这个:
def showColumn(xs: List[String]): String = xs.map(x => if(x == "") " " else x).mkString
或者,或者:
def showColumn(xs: List[String]): String = xs.map(x => if(x.isEmpty) " " else x).mkString
两者都通过将列表中的空字符串更改为空格,然后将列表中的每个字符串合并为单个字符串来工作。
如果您绝对必须将其设为递归函数,则不是 尾递归 的解决方案将如下所示:
def showColumn(xs: List[String]): String = xs match {
case Nil => ""
case x :: xs1 => (if(x.isEmpty) " " else x) + showColumn(xs1)
}
最后,tail-recursive 版本稍微复杂一些,因为它使用了一个辅助函数:
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, "")
}