[Haskell-cafe] Optimization fun

Creighton Hogg wchogg at gmail.com
Sat Feb 10 16:02:09 EST 2007

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.

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)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070210/cd65a7f6/attachment.htm

More information about the Haskell-Cafe mailing list