Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Haskell

    foldl' (+) 0 [1..1000000000]
You could use sum, but that will eat up a lot of RAM because of the laziness.

EDIT: For the fun of it, I decided to do the same in a slightly more esoteric language, so here's a Prolog version (given that your stack is big enough)

    rangesum(0,0).
    rangesum(N,X) :- M is N - 1, rangesum(M,Y), X is Y + N.

    ?- rangesum(1000000000, X), write(X).


sum is fine in GHC. It is specialised for Integer. GHCi uses naive sum though.


I tried sum in GHC and it ate up my 16 gigs of ram and then crashed. I'm a noob so maybe I did something wrong, but my code was:

    main = do
        putStrLn $ show  $ sum [1..1000000000]


Pass GHC the -O2 option to turn on optimizations. You need the strictness analyzer to run so that it can determine that sum is strict, otherwise you get a space leak.


Thank you :)


Good to know that. I was trying that code in GHCi, which explains a few things now.


GHC's strictness analyzer will recognize that sum is strict for Integer and optimize the laziness away. It will only cause a space leak when optimizations are turned off.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: