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

Re: [scala] How would you write Stream.cycle?

by tmorris :: Rate this Message:

Reply to Author | View in Thread

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Paul Chiusano wrote:
| 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
|
|
|
Do note that Haskell is a little different, with early failure on []
instead of non-termination. In any case, this seems fine:

scala> def cycle[A](as: Stream[A]): Stream[A] = if(as.isEmpty)
error("cycle on empty") else as append cycle(as)
cycle: [A](Stream[A])Stream[A]

scala> cycle(cons(1, cons(2, cons(3, empty)))).head
res16: Int = 1

- --
Tony Morris
http://tmorris.net/

Real-world problems are simply degenerate cases of pure mathematical
problems.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFIdUytmnpgrYe6r60RAm6hAJ43l994LZHMkbCO0AsFUE/oV67rPQCgqQgW
/Vb6Hw1IzC1o7PNHTHTkS5U=
=qpdi
-----END PGP SIGNATURE-----

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

LightInTheBox - Buy quality products at wholesale price!