向您学习 Haskell 谈论 foldl'
作为foldl
的替代品因为foldl
容易发生堆栈溢出。
foldl (+) 0 (replicate 1000000 1)
应该堆栈溢出,但它不在我的机器上。 为什么不? 即使我将这个数字增加到 1000 万,它也不会溢出。它只会占用大量内存,直到我的 OS X 计算机无法使用并且我必须重新启动它。 foldl
而不是 foldl'
?以我的经验foldl'
“正常工作”而 foldl
基本上可以使我的计算机崩溃(见上文)。 foldr
没有类似的东西.为什么不能foldr
堆栈溢出,为什么没有foldr'
? 最佳答案
它不会因堆栈溢出而崩溃,因为默认情况下堆栈现在是无限的。也就是说,默认的 GHC 运行时行为是允许堆栈无限增长——没有可以触发堆栈溢出错误的界限。
https://ghc.haskell.org/trac/ghc/ticket/8189
以下是它如何工作的描述:
Thread stacks (including the main thread's stack) live on the heap. As the stack grows, new stack chunks are added as required; if the stack shrinks again, these extra stack chunks are reclaimed by the garbage collector. The default initial stack size is deliberately small, in order to keep the time and space overhead for thread creation to a minimum, and to make it practical to spawn threads for even tiny pieces of work.
关于haskell - 关于折叠和堆栈溢出的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28482106/