Scalaで無限リスト:Haskellライクに

ScalaにはStreamという無限リストがあるんだけど、微妙に使いづらい、というか分かりづらい。Haskellでいうcycleはどうだ、とかよく忘れるのでメモ。

1def repeat[T](a:T) = Stream.const(a)
2def cycle[T](a:Iterable[T]) = Stream.const(a).flatMap(v=>v)
3def iterate[T](f:T => T,  x:T):Stream[T] = Stream.cons(x, iterate(f, f(x)))
4def replicate[T](n:int, elem:T) = Stream.make(n, elem)

こんな感じかな。cycleは結構使うから、Streamに標準でありそうな気がするんだけど、ないような。というわけで上のような定義となる。

 1repeat(1) take 10 print
 2// => 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, Stream.empty
 3
 4cycle(1 to 4) take 10 print
 5// => 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, Stream.empty
 6
 7iterate((x:int)=>x+1, 0) take 10 print
 8// => 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, Stream.empty
 9
10replicate(3, 1) take 10 print
11// => 1, 1, 1, Stream.empty

うんうん。

comments powered by Disqus