从Functional Programming in Scala看forever组合器
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)
}
}正如书中解释的那样,我遇到了一个StackOverflow。
然后,我添加了一个count变量,每次访问t时递增该变量:
var count = 0
def forever[A, B](a: F[A]): F[B] = {
lazy val t = { println(count); count = count + 1; forever(a) }
}然后,我创建了一个ScalaTest测试:
"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))
}
}运行上述测试3次后,每次都会在~1129/1130失败。
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为什么它会在崩溃之前达到这个数字?另外,我如何推断forever的每次执行占用了多少堆栈内存?
发布于 2014-02-25 16:36:45
由于堆栈的大小,它会达到这个数字。可以使用-Xss设置大小,默认值因平台和VM/版本的不同而不同。但一般来说,当你得到一个StackOverflowError时,你应该尝试修复你的代码中的问题,而不是你的设置。在这种情况下,我将使用trampolining来防止堆栈溢出。可以在这里找到一个非常好的解释:http://blog.higher-order.com/assets/trampolines.pdf
https://stackoverflow.com/questions/22003986
复制相似问题