[Haskell-Cafe] Quick question for a slow program
Lanny Ripple
lanny at cisco.com
Sat Jun 7 17:34:37 EDT 2008
The second prime generator on this page
http://www.haskell.org/haskellwiki/Prime_numbers
is quick and easy. I keep it nearby for all those sudden attacks of
needing to solve yet another projecteuler problem.
-ljr
Slavomir Kaslev wrote:
> 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.
>
More information about the Haskell-Cafe
mailing list