StackOverflow on the forever combine

Looking for the forever Scala Functional Programming combinator :

trait AddlCombinators[F[_]] extends Monad[F] with Functor[F] {
      def forever[A, B](a: F[A]): F[B] = {
        lazy val t: F[B] = forever(a)
        flatMap(a)(_ => t)
      }
}

I came across StackOverflow, as the book explains.

Then I added a variable count, incrementing it every time I tget access:

var count = 0
def forever[A, B](a: F[A]): F[B] = {
  lazy val t = { println(count); count = count + 1; forever(a) }
}

Then I created a ScalaTest test:

 "running forever" should "throw a StackOverflow exception" in {
        val listCombinator = new AddlCombinators[List] {

        // omitted implementation of `Monad[List]` and `Functor[List]`
        }    
        listCombinator.forever(List(1))
      }
}

After performing the above test 3 times, it fails at ~ 1129/1130 each time.

1129
[info] TestCombinators:
[info] running forever
[trace] Stack trace suppressed: run last test:testOnly for the full output.
[error] Could not run test test.TestCombinators: java.lang.StackOverflowError

Why does he rise to this number before a failure? Also, how can I explain how much memory the stack takes at runtime forever?

+3
source share
1 answer

- . -Xss, VM/Version. , StackOverflowError, , . trampolining, . : http://blog.higher-order.com/assets/trampolines.pdf

+2

All Articles