Okay, so I made a small modification that seems to have made a whole lot of difference to haskell. Here is how it goes:
I implemented the Sieve of Eratosthenes for Prob 10 from project euler. Here's how it goes:
primesBelowN :: Integer -> [Integer]
primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, 1]]
where f x = foldr g True [2..truncate(sqrt(fromInteger x))]
where g t ac = (x `rem` t /= 0) && ac
main = print $ sum $ primesBelowN 2000000
Compiling it with ghc, I get a runtime of 8.95 seconds:
$ ghc -O3 010SummationOfPrimes.hs
$ time 010SummationOfPrimes
142913828922
8.739u 0.122s 0:08.95 98.8% 0+0k 2384+0io 1pf+0w
I thought I could optimize the code by taking advantage of haskell's lazy evaluation in the g
function. Could be done (or so I thought) by simply placing the ac
as the first argument to &&
, so that it does not compute the inequality if ac == False
:
primesBelowN :: Integer -> [Integer]
primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, 1]]
where f x = foldr g True [2..truncate(sqrt(fromInteger x))]
where g t ac = ac && (x `rem` t /= 0)
main = print $ sum $ primesBelowN 2000000
Surprisingly, it makes the program 4X Slower!. The runtime now, noticeably larger, is 30.94s:
$ ghc -O3 010SummationOfPrimes.hs
$ time 010SummationOfPrimes
142913828922
30.765u 0.157s 0:30.94 99.9% 0+0k 2384+0io 1pf+0w
I have no idea what went wrong... any hints/suggestions/answers? Thanks in advance!
EDIT
So, I was playing with this when I toppled over another thing. Looks like it is easy to land into infinite loops if I just modulate my function like this:
primesBelowN :: Integer -> [Integer]
primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, 1]]
where f x = foldr g True [m | m <- [2..],
m <= truncate(sqrt(fromInteger x))]
where g t ac = (x `rem` t /= 0) && ac
main = print $ sum $ primesBelowN 2000000
The process memory just keeps exploding in this case to huge numbers (80Gig, before I killed it), without any outputs:
$ ghc -O3 010SummationOfPrimes.hs
$ time 010SummationOfPrimes
^C20.401u 7.994s 0:28.42 99.8% 0+0k 2384+0io 1pf+0w
Any ideas what's going wrong now?