This is what I get in the console:
ghci> sum $ takeWhile (<10000000) [1..]
49999995000000
(11.96 secs, 2174569400 bytes)
That’s over 2GB! I would imagine that sum can discard whatever it has already summed. How would you write this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You’re creating ten million
Integers, and a lot of list cells. Also, you’re running interpreted code, if you ran it through the compiler, that would reduce the allocation somewhat.The main problem is that the interpreter doesn’t optimise at all, so the
sumuses the lazy variant that builds a huge thunk.sumdiscards the part of the list it has consumed just fine, but it replaces it with a thunk to compute the result afterward, sobecomes
afterward. That’s not the optimal substitution, since addition of
Integers is strict.At the ghci prompt, you should write
to fix that. In a compiled (with optimisations, of course) programme,
sumwill work fine.