Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

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 ?

like image 686
John Threepwood Avatar asked Sep 06 '12 12:09

John Threepwood


People also ask

How do you repeat a element and time in a list?

To repeat the elements of the list n times, we will first copy the existing list into a temporary list. After that, we will add the elements of the temporary list to the original list n times using a for loop, range() method, and the append() method.

How do you repeat a list and time in Python?

Repeat Each Element in a List in Python using itertools. repeat() This particular problem can also be solved using python inbuilt functions of itertools library. The repeat function, as the name suggests does the task of repetition and grouping into a list is done by the from_iterable function.

Which operator repeats a list given number of times?

Using * This is the most used method. Here we use the * operator which will create a repetition of the characters which are mentioned before the operator.


3 Answers

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.

like image 148
kiritsuku Avatar answered Oct 15 '22 13:10

kiritsuku


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

Works like a charm.

like image 15
Danilo M. Oliveira Avatar answered Oct 15 '22 13:10

Danilo M. Oliveira


Using tabulate like this,

List.tabulate(3)(_ => "foo")
like image 13
elm Avatar answered Oct 15 '22 14:10

elm