Scalaで無限リスト:Haskellライクに
ScalaにはStreamという無限リストがあるんだけど、微妙に使いづらい、というか分かりづらい。Haskellでいうcycleはどうだ、とかよく忘れるのでメモ。
SCALA:
- def repeat[T](a:T) = Stream.const(a)
- def cycle[T](a:Iterable[T]) = Stream.const(a).flatMap(v=>v)
- def iterate[T](f:T => T, x:T):Stream[T] = Stream.cons(x, iterate(f, f(x)))
- def replicate[T](n:int, elem:T) = Stream.make(n, elem)
こんな感じかな。cycleは結構使うから、Streamに標準でありそうな気がするんだけど、ないような。というわけで上のような定義となる。
SCALA:
- repeat(1) take 10 print
- // => 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, Stream.empty
- cycle(1 to 4) take 10 print
- // => 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, Stream.empty
- iterate((x:int)=>x+1, 0) take 10 print
- // => 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, Stream.empty
- replicate(3, 1) take 10 print
- // => 1, 1, 1, Stream.empty
うんうん。
About this entry
You’re currently reading “Scalaで無限リスト:Haskellライクに,” an entry on inforno
- Published:
- 02.09.08 / 11pm
- Tags:
- scala




No comments
Jump to comment form | trackback uri [?]