[scala] 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)

동일한 작업을 수행하는 기본 제공 방법도 있습니까?



답변

보기 (=>를 ELEM) scala.collection.generic.SeqFactory.fill (N INT) 모음의 데이터 구조가 같은 것으로 Seq, Stream, Iterator등, 확장 :

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

경고 Scala 2.7에서는 사용할 수 없습니다.


답변

사용하여 tabulate다음과 같이

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


답변

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

매력처럼 작동합니다.


답변

내가 생각하는 flatMap을 에뮬레이트하는 또 다른 답변이 있습니다 (이 솔루션은 duplicateN을 적용 할 때 Unit을 반환한다는 것을 알았습니다)

 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)(_) }

그러나 이것은 오히려 미리 결정된 목록에 대한 것이며 각 요소를 n 번 복제하고 싶습니다.


답변