如何创建具有相同元素 n 次的列表?

如何创建具有相同元素 n 次的列表?

手动执行:

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)

是否也有一种内置的方式来做同样的事情?

56918 次浏览

See scala.collection.generic.SeqFactory.fill(n:Int)(elem: =>A) that collection data structures, like Seq, Stream, Iterator and so on, extend:

scala> List.fill(3)("foo")
res1: List[String] = List(foo, foo, foo)

WARNING It's not available in Scala 2.7.

I have another answer which emulates flatMap I think (found out that this solution returns Unit when applying duplicateN)

 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

Using tabulate like this,

List.tabulate(3)(_ => "foo")
(1 to n).map( _ => "foo" )

Works like a charm.