Scala: 関数をn回適用した結果のリストを作る
scala.collection.immutable.Stream を使うと簡単にできる。
以下は、適当な文字列の左右を「#」で囲む関数を 1回, 2回, ... と適用した結果をリストにして返す例。
(Scala 2.10, REPLで実行)
scala> def f(s: String) = s"#${s}#"
f: (s: String)String
scala> def g(s: String): Stream[String] = s #:: g(f(s))
g: (s: String)Stream[String]
scala> g("x").tail.take(5).toList
res0: List[String] = List(#x#, ##x##, ###x###, ####x####, #####x#####)
2013-08-30 追記
今回の目的であれば、iterate メソッドを使った方が適しているとご指摘をいただきました。
List#iterate, Iterator#iterate, Stream#iterate を使った例です。
scala> def f(s: String) = s"#${s}#"
f: (s: String)String
scala> List.iterate(f("x"), 5)(f)
res0: List[String] = List(#x#, ##x##, ###x###, ####x####, #####x#####)
scala> Iterator.iterate("x")(f).drop(1).take(5).toList
res19: List[String] = List(#x#, ##x##, ###x###, ####x####, #####x#####)
scala> Stream.iterate("x")(f).tail.take(5).toList
res26: List[String] = List(#x#, ##x##, ###x###, ####x####, #####x#####)
こちらの方が素敵ですね。
iterate使えば
返信削除コメントありがとうございます。追記してみました。
返信削除