scala 如何创建具有 n 次相同元素的列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12300165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a list with the same element n-times?
提问by John Threepwood
How to create a list with the same element n-times ?
如何创建具有相同元素 n 次的列表?
Manually implementnation:
手动实现:
scala> def times(n: Int, s: String) =
| (for(i <- 1 to n) yield s).toList
times: (n: Int, s: String)List[String]
scala> times(3, "foo")
res4: List[String] = List(foo, foo, foo)
Is there also a built-in way to do the same ?
是否也有内置的方法来做同样的事情?
回答by kiritsuku
See A):CC[A]" rel="noreferrer">scala.collection.generic.SeqFactory.fill(n:Int)(elem: =>A)that collection data structures, like Seq, Stream, Iteratorand so on, extend:
见A):CC[A]" rel="noreferrer">scala.collection.generic.SeqFactory.fill(正的:int)(ELEM:=> A)该集合的数据结构,例如Seq,Stream,Iterator等等,延伸:
scala> List.fill(3)("foo")
res1: List[String] = List(foo, foo, foo)
WARNINGIt's not available in Scala 2.7.
警告它在 Scala 2.7 中不可用。
回答by elm
Using tabulatelike this,
tabulate像这样使用,
List.tabulate(3)(_ => "foo")
回答by Danilo M. Oliveira
(1 to n).map( _ => "foo" )
Works like a charm.
奇迹般有效。
回答by Tomás Duhourq
I have another answer which emulates flatMap I think (found out that this solution returns Unit when applying duplicateN)
我有另一个我认为模拟 flatMap 的答案(发现该解决方案在应用重复 N 时返回 Unit)
implicit class ListGeneric[A](l: List[A]) {
def nDuplicate(x: Int): List[A] = {
def duplicateN(x: Int, tail: List[A]): List[A] = {
l match {
case Nil => Nil
case n :: xs => concatN(x, n) ::: duplicateN(x, xs)
}
def concatN(times: Int, elem: A): List[A] = List.fill(times)(elem)
}
duplicateN(x, l)
}
}
}
def times(n: Int, ls: List[String]) = ls.flatMap{ List.fill(n)(_) }
but this is rather for a predetermined List and you want to duplicate n times each element
但这更像是一个预先确定的列表,并且您想将每个元素复制 n 次

