Expand the size of a List by N

Viewed 107

I am having difficulty in phrasing this question so I apologies for the vague sounding title.

I started learning Scala today. I would like to generate a list of elements, and then multiply that list by a factor N, with the result as follows:

List(1, 2, 3, 4) * N -> List(1, 2, 3, 4, 1, 2, 3, 4) (where N = 2)

In Python, I would just do the following which would yield what I am looking for:

my_list = [1, 2, 3, 4] * 2 

However, this does not work in Scala.

3 Answers

Try List.fill

List.fill(2)(List(1, 2, 3, 4)).flatten
// : List[Int] = List(1, 2, 3, 4, 1, 2, 3, 4)

or provide extension method to mimic Python, something like

extension (l: List[Int]) 
  def *(n: Int): List[Int] = List.fill(n)(l).flatten

List(1, 2, 3, 4) * 2
// : List[Int] = List(1, 2, 3, 4, 1, 2, 3, 4)

You can do something like that:

val l = List(1, 2, 3, 4)
val n = 2
val result = (1 to n)
  .flatMap(_ => l)
  .toList

Another option you have is:

val l = List(1, 2, 3, 4)
val length = l.length
List.tabulate(length * n)(i => l(i % length))
Related