ScalaにはStreamという無限リストがあるんだけど、微妙に使いづらい、というか分かりづらい。Haskellでいうcycleはどうだ、とかよく忘れるのでメモ。
scala code
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 code
repeat(1) take 10 print// => 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, Stream.emptycycle(1 to 4) take 10 print// => 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, Stream.emptyiterate((x:int)=>x+1, 0) take 10 print// => 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, Stream.emptyreplicate(3, 1) take 10 print// => 1, 1, 1, Stream.empty
うんうん。
No comments yet
trackback uriLeave a Comment