--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
I believe in this case you would also avoid a memory leak [...]
If you want a Stream that just repeats the same values over and over again, Stream.continually is not the best way. It always produces a linear structure, never a circular structure. So instead of O(1) memory usage, you get O(n) memory usage.Stream doesn't have a built-in method that will give you a true circular stream. Here's what I use to get one:implicit class RichStream[T](xs: Stream[T]) {def circular: Stream[T] = {lazy val circle: Stream[T] = xs #::: circlecircle}}
To see that this is truly circular, we can insert a println:scala> Stream.from(1).map{x => println(x); x}.take(3).circular.take(10).force123res2: scala.collection.immutable.Stream[Int] = Stream(1, 2, 3, 1, 2, 3, 1, 2, 3, 1)By contrast,scala> Stream.continually(Stream(1, 2, 3).map{x => println(x); x}).flatten.take(10).force1231231231res6: scala.collection.immutable.Stream[Int] = Stream(1, 2, 3, 1, 2, 3, 1, 2, 3, 1)
implicit class RichStream[T](xs: Stream[T]) {def circular: Stream[T] = {lazy val circle: Stream[T] = xs #::: circlecircle}}I don't think I've ever seen a `lazy val` inside a method. A recursive lazy val even. Does it do what I think it does?
Could you shorten it even more to the following?implicit class RichStream[T](s: Stream[T]) {def circular: Stream[T] = s #::: circular}
re-running your example I only see "1 2 3" printed once like in your original example.
Could you shorten it even more to the following?implicit class RichStream[T](s: Stream[T]) {def circular: Stream[T] = s #::: circular}
On Thu, May 9, 2013 at 9:05 AM, Nils Kilden-Pedersen <nil...@gmail.com> wrote:
implicit class RichStream[T](xs: Stream[T]) {def circular: Stream[T] = {lazy val circle: Stream[T] = xs #::: circlecircle}}I don't think I've ever seen a `lazy val` inside a method. A recursive lazy val even. Does it do what I think it does?I don't know. Does it? ;-)
If you omit `lazy` here, you get this error: "error: forward reference extends over definition of value circle". The compiler is being overly picky, since the recursive reference is inside #:::'s by-name parameter, so it isn't evaluated until later. So in this case `lazy` just avoids the forward reference check, rather than adding any real meaning.(see SLS, top of Chapter 4: "there is a restriction on forward references in blocks...")It occurs to me just now that my code above can actually be shortened to just:implicit class RichStream[T](s: Stream[T]) {lazy val circular: Stream[T] = s #::: circular}I tested this and it works the same.