[Haskell-cafe] Why does this blow the stack?

Don Stewart dons at galois.com
Fri Dec 21 17:30:27 EST 2007


dbenbenn:
> On Dec 21, 2007 12:02 PM, Don Stewart <dons at galois.com> wrote:
> > There's no good reason for the accumulator for Integer to be lazy,
> > especially when you see that adding an upper bound  (enumFromTo) or
> > using Int uses a strict accumulator.
> >
> > I've filled a bug report and fix for this.
> >
> >     http://hackage.haskell.org/trac/ghc/ticket/1997
> >
> > there's an ad hoc sprinkling of strict and lazy Num ops for Integer
> > through the base library, while Int is fairly consistently strict.
> 
> Thanks for fixing this.  But doesn't GHC have strictness analysis?
 
Sure does!

> Even if there was consistent strictness for Integer in the base
> library, that wouldn't help for code not in the base library.  In
> other words, I want to be able to define
> 
> mysum :: (Num a) => [a] -> a
> mysum = foldl (+) 0
> 
> in my own programs, and have GHC automatically make it strict if "a"
> happens to be Int or Integer.  Is there any chance of GHC getting that
> ability?

Thankfully, GHC does that already :)

    mysum :: (Num a) => [a] -> a
    mysum = foldl (+) 0

    main = print (mysum [1..10000000])

In ghc 6.6,

    $ time ./A +RTS -M20M        
    Heap exhausted;
    Current maximum heap size is 19996672 bytes (19 Mb);
     use `+RTS -M<size>' to increase it.

and in GHC 6.8, ghc can see through to the strictness of (+)

    $ time ./A +RTS -M20M      
    50000005000000
    ./A +RTS -M20M  0.95s user 0.00s system 99% cpu 0.959 total

The problem here was an explicit recusive loop though, 
with just not enough for the strictness analyser to get going.

-- Don


More information about the Haskell-Cafe mailing list