同じ要素を持つリストを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)
同じことをする組み込みの方法もありますか?
同じ要素を持つリストを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)
同じことをする組み込みの方法もありますか?
回答:
参照:(=> Aの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では利用できません。
(1 to n).map( _ => "foo" )
魅力のように機能します。
_
実際には重要ではないため。あなたは何ができるn to 1 by -1
、-1 to -n by -1
など
fill
メソッドの実装でさえ、一時変数を内部的に構築します。一時変数は、リストに適切な量を生成する限り、その値は重要ではありません。だから私は未使用を気にしません _
。
私が思う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回複製したい