将List的每一项打印N次

我是 Scala/函数式编程的新手,想了解我的以下解决方案是否适合函数式编程世界。如果有人可以建议我更好的方法,我将不胜感激。

问题陈述:打印一个列表的每一项,n次

解决方案:

import scala.collection.mutable.ListBuffer

object ListReplication extends App {


  def printNTimes(items: List[Int], n: Int): ListBuffer[Int] = {

    var outputList = new ListBuffer[Int]

    def storeNTime(item: Int): Unit = {

      for (_ <- 1 to n) outputList += item

    }

    for (item <- items) storeNTime(item)

    outputList
  }

  val result = printNTimes(items = List(1,2,4), n = 3)
  println(result)
}

回答

使用不可变类型总是更好。所以我将返回类型更改为List[Int]. 你可以这样做:

def printNTimes(items: List[Int], n: Int): List[Int] = {
  items.flatMap(i => Vector.fill(n)(i))
}

或者:

def printNTimes(items: List[Int], n: Int): List[Int] = {
  items.flatMap(Vector.fill(n)(_))
}

然后运行:

println(printNTimes(List(1,2,4), 3))

将输出:

List(1, 1, 1, 2, 2, 2, 4, 4, 4)

  • @Sumit three advices; Forbid your self for using any kind of mutability. Check the [**Scaladoc**](https://www.scala-lang.org/api/current/). Search for some book / tutorial / course that guides you step by step into FP. - Happy coding!

以上是将List的每一项打印N次的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>