[Haskell-Cafe] Quick question for a slow program

Slavomir Kaslev slavomir.kaslev at gmail.com
Sat Jun 7 05:26:17 EDT 2008


Hello,

I was just brushing my haskell-fu skills writing a solution for Google
Treasure Hunt Problem 4. Hers is what it looks like:

> primes = sieve [2..]
>     where
>       sieve (p:xs) = p : sieve [x | x <- xs, x `mod` p /= 0]
>
> sumOf n l = sum (take n l) : sumOf n (tail l)
>
> find l = foldl1 aux l
>     where
>       aux (x:xs) (y:ys) | x == y = x : aux xs ys
>                         | x < y  = aux xs (y:ys)
>                         | x > y  = aux (x:xs) ys
>
> puzzle = find (reverse [primes, p7, p17, p41, p541])
>     where
>       p7 = sumOf 7 primes
>       p17 = sumOf 17 primes
>       p41 = sumOf 41 primes
>       p541 = sumOf 541 primes
>
> main = do mapM (\x -> putStrLn $ show x) puzzle

While the code is quite readable and straight forward it is as slow as
tortoise with four legs broken. What optimizations would you suggest,
while still keeping the code clear and highlevel?

Thank you in advance.

Cheers.

-- 
Slavomir Kaslev


More information about the Haskell-Cafe mailing list