From: Logo Logo <saraslogo@gmail.com>

Hi,

For the following error:

Stack space overflow: current size 8388608 bytes.
Use `+RTS -Ksize -RTS' to increase it.

I want to find out the culprit function and rewrite it tail-recursively. Is
there a way to find out which function is causing this error other
than reviewing the code manually?

I'd like to point out that a stack-space overflow in Haskell isn't quite the same thing as in other functional languages.  In particular, it's possible for tail-recursive functions to overflow the stack because of laziness.

Consider this tail-recursive sum function:

> trSum :: [Int] -> Int
> trSum l = go 0 l
>  where
>   go acc [] = acc
>   go acc (x:xs) = go (acc+x) xs

It's tail-recursive.  But if you enter this in ghci and run it, you'll find that it uses increasing stack space, and will likely cause a stack overflow for large enough inputs.  The problem is that the accumulator 'acc' isn't strict and builds up a thunk of the form:

0+n1+n2+...+nn

The solution is to add strictness.  For this example, a '!' on the accumulator will do.  GHC will sometimes spot cases where extra strictness is helpful (it'll figure this one out when compiled with -O), but it often needs help.

I'd recommend Edward Yang's series of blog posts about debugging, space leaks, and the Haskell heap.  One useful article is http://blog.ezyang.com/2011/05/anatomy-of-a-thunk-leak/ , but you may want to start at the beginning of the heap series.

John L.