Sum*_*mit 1 functional-programming scala list
我是 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)
}
Run Code Online (Sandbox Code Playgroud)
使用不可变类型总是更好。所以我将返回类型更改为List[Int]. 你可以这样做:
def printNTimes(items: List[Int], n: Int): List[Int] = {
items.flatMap(i => Vector.fill(n)(i))
}
Run Code Online (Sandbox Code Playgroud)
或者:
def printNTimes(items: List[Int], n: Int): List[Int] = {
items.flatMap(Vector.fill(n)(_))
}
Run Code Online (Sandbox Code Playgroud)
然后运行:
println(printNTimes(List(1,2,4), 3))
Run Code Online (Sandbox Code Playgroud)
将输出:
List(1, 1, 1, 2, 2, 2, 4, 4, 4)
Run Code Online (Sandbox Code Playgroud)