[Haskell-cafe] Optimization fun
wchogg at gmail.com
Sat Feb 10 16:02:09 EST 2007
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.
-- Naive way to calculate prime numbers, testing each new n to see if it has
prime factors less than sqrt(n).
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...
More information about the Haskell-Cafe