How to create a list with the same element n-times?

Scala

Scala Problem Overview


How to create a list with the same element n-times ?

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 ?

Scala Solutions


Solution 1 - Scala

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.

Solution 2 - Scala

Using tabulate like this,

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

Solution 3 - Scala

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

Works like a charm.

Solution 4 - Scala

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohn ThreepwoodView Question on Stackoverflow
Solution 1 - ScalakiritsukuView Answer on Stackoverflow
Solution 2 - ScalaelmView Answer on Stackoverflow
Solution 3 - ScalaDanilo M. OliveiraView Answer on Stackoverflow
Solution 4 - ScalaTomás DuhourqView Answer on Stackoverflow