sum[1..100000] --> stack overflow in GHC, but not in Hugs?

Don Stewart dons at galois.com
Sun Nov 23 13:50:41 EST 2008


shoot.spam:
> Hi,
> 
> Please bear with a very basic question. I am trying to 'learn me a
> Haskell for great good' using Hutton's book and some online tutorials.
> I started off with Hugs and recently used GHC (to use the 'let a  =
> .." syntax interactively, which Hugs doesn't allow perhaps).
> 
> There's a simple issue I am having with GHC. sum[1..100000] works fine
> on Hugs, however, the same in GHCi generates a stack overflow
> exception. I am trying to figure out what's going on.
> 
> 
> Prelude> sum[1..100000]
> 5000050000
> Prelude> sum[1..1000000]
> *** Exception: stack overflow
> Prelude>
> 
> ________________________
> 
> Hugs> sum[1..10000]
> 50005000
> Hugs> sum[1..100000]
> 5000050000
> Hugs>
> 
> 
> Thanks in anticipation.
> 
> Best regards,
> Vishal Belsare
> 

Probably the simplest thing to do is compile the code,

    $ cat A.hs
    main = print (sum [1..1000000])

    $ ghc -O2 A.hs

    $ time ./a.out 
    500000500000
    ./a.out  0.09s user 0.00s system 96% cpu 0.100 total

As Duncan pointed out, Hugs has a non-standard strict implementation of
sum, which is nice, but breaks the spec if you do it at every type.

GHC with optimisations determines that indeed this should be strict,
replacing sum with a specialised version, but those optimisations are
enabled in the compiler, not ghci.

-- Don


More information about the Glasgow-haskell-users mailing list