scalaz/scalaz — Issue #53: Stackoverflow error when traversing a Stream with a State
Author: etorreborre
Created: 2011-12-02 06:08:56+00:00
State: open

I have the following example (similar to issue #40, also with scalaz-core-6.0.4-SNAPSHOT):

```
val counter = state((i:Int) => (i+1, i+1))
val traversed: State[Int, Stream[Int]] = (Stream.from(5)).take(10000).traverse[({type l[a]=State[Int, a]})#l, Int](i => counter)
val started: Stream[Int] = traversed ! 5
val result: Stream[Int] = started.take(3)
result.toList must_== List(6, 7, 8)
```

And I get a SOE:
```
[error] scalaz.Foldable$$anon$13.foldRight(Foldable.scala:95)
[error] scalaz.Foldable$$anon$13$$anonfun$foldRight$6.apply(Foldable.scala:95)
[error] scalaz.Traverse$$anon$4$$anonfun$traverse$6.apply(Traverse.scala:31)
[error] scalaz.Traverse$$anon$4$$anonfun$traverse$6.apply(Traverse.scala:31)
```

At first I thought that `foldRight` was causing the issue and I should just use `foldLeft`:

```
implicit def StreamTraverse: Traverse[Stream] = new Traverse[Stream] {
def traverse[F[_]: Applicative, A, B](f: A => F[B], as: Stream[A]): F[Stream[B]] =
as.foldl[F[Stream[B]]]((Stream.Empty: Stream[B]) pure)((ys, x) => implicitly[Apply[F]].apply(f(x) map ((a: B) => (b: Stream[B]) => a #:: b), ys))
}
```

Alas, I still get a SOE:

```
[error] scalaz.States$$anon$1.apply(State.scala:45)
[error] scalaz.State$$anonfun$map$1.apply(State.scala:8)
[error] scalaz.State$$anonfun$map$1.apply(State.scala:8)
[error] scalaz.States$$anon$1.apply(State.scala:45)
```

I think that something escapes my understanding here.

I also note that I'm [not the only one to face this issue](https://groups.google.com/d/topic/scalaz/QPUs6TWTAm4/discussion) but I couldn't find out if others have solved it already.

Thanks.