字符串的后缀列表以及它们之前在 Scala 中重复的次数

问题描述 投票:0回答:1

如果我们有一个字符串列表,请创建一个新列表,其中每个重复元素都有一个重复次数的后缀,并保留顺序。

示例: List("a","a","a","b","b","c","C") 应该变成 List("a","a.1","a.2", “b”,“b.1”,“c”,“C”)

我可以循环遍历每个元素,更新一个映射来计算每个元素出现的次数,然后将每个元素添加到列表中,但必须有更多的“Scala 方式”来执行此操作。

scala loops dictionary immutability
1个回答
0
投票

您可以使用递归遍历和模式匹配,用普通的 scala 编写类似的东西。它不仅仅是 scala,而是一种函数式方式。

val initList = List("a", "a", "a", "b", "b", "c", "C")

@tailrec
def loop(list: List[String], res: Vector[List[String]] = Vector.empty): List[String] = {
  list match {
    case Nil =>
      res.flatMap(_.reverse.zipWithIndex.map { case (str, idx) => if (idx == 0) str else s"$str.$idx" }).toList
    case xs =>
      val (same, rest) = xs.span(_ == xs.head)
      loop(rest, res :+ same)
  }
}

loop(initList) should contain theSameElementsInOrderAs Seq("a", "a.1", "a.2", "b", "b.1", "c", "C")

或者使用 fs2

更优雅
val initList = List("a", "a", "a", "b", "b", "c", "C")

val result =
  fs2.Stream
    .emits(initList)
    .groupAdjacentBy(identity)
    .map { case (_, groups) => groups }
    .map(_.zipWithIndex.map { case (str, idx) => if (idx == 0) str else s"$str.$idx" })
    .flatMap(fs2.Stream.chunk)
    .toList

result should contain theSameElementsInOrderAs Seq("a", "a.1", "a.2", "b", "b.1", "c", "C")
© www.soinside.com 2019 - 2024. All rights reserved.