score:191

Accepted answer

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.

score:1

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

score:13

Using tabulate like this,

List.tabulate(3)(_ => "foo")

score:15

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

Works like a charm.


Related Query

More Query from same tag