« Return to Thread: [scala] How would you write Stream.cycle?

[scala] How would you write Stream.cycle?

by Paul Chiusano-2 :: Rate this Message:

Reply to Author | View in Thread

I am trying to write a function which cycles a Stream, s, that is,
forms the infinite stream s ++ s ++ ... Is it possible to do this
without writing a custom Stream implementation?

Here was my first attempt:

 def cycle[E](s: => Stream[E]): Stream[E] = {
      lazy val stream = s
      stream.append(cycle(stream))
 }

Nope! This bombs with a stack overflow. I was hoping it would work
just like Haskell:

Prelude> let cycle x = x ++ cycle x
Prelude> take 11 (cycle [1,2,3,4])
[1,2,3,4,1,2,3,4,1,2,3]

But Stream.append evaluates its argument fully, so that leads to
infinite recursion.

Is there any way to do this in Scala and at least keep the spirit of
the Haskell version?

Paul

 « Return to Thread: [scala] How would you write Stream.cycle?

LightInTheBox - Buy quality products at wholesale price!