Hello Haskell-ers,
So a friend and I were thinking about making code faster in Haskell, and I was wondering if there was a way to improve the following method of generating the list of all prime numbers. It takes about 13 seconds to run, meanwhile my friend's C version took
0.1. I'd love to learn a bit more about how to optimize Haskell code.
Cheers,
Creighton Hogg
-- Naive way to calculate prime numbers, testing each new n to see if it has prime factors less than sqrt(n).
import Data.List
primes = 2:(foldr (\x y -> if isPrime x then x:y else y) [] [3..])
where isPrime x = foldl' (\z y -> z && (if x `mod` y == 0 then False else True)) True (take (floor $ sqrt $ fromIntegral x) primes)