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

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

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


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

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


うんうん。


About this entry