3 ms·
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
by tsahyt 13y ago
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).
- dons 13y agosum is fine in GHC. It is specialised for Integer. GHCi uses naive sum though.
- tsahyt 13y agoGood to know that. I was trying that code in GHCi, which explains a few things now.
- cgag 13y agoI 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]
- TheCoelacanth 13y agoPass 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.
- cgag 13y agoThank you :)
- TheCoelacanth 13y agoGHC'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.