I've recently been going through the Learn You a Haskell for Great Good guide and as practice I wanted to solve Project Euler Problem 5 with it, which specifies:
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
I decided to first write a function determining whether a given number is divisible by these numbers:
divisable x = all (\y -> x `mod` y == 0)[1..20]
Then I calculated the smallest one using head
:
sm = head [x | x <- [1..], divisable x]
And finally wrote the line to display the result:
main = putStrLn $ show $ sm
Unfortunately this took about 30 seconds to finish. Doing the same thing with the numbers 1 to 10 yields a result almost immediately, but then again the result is much smaller than the solution for 1 to 20.
I solved it earlier in C and there the result for 1 to 20 was also calculated almost instantly. This leads me to believe I'm misunderstanding how to interpret this problem for Haskell. I looked through other people's solutions and found this:
main = putStrLn $ show $ foldl1 lcm [1..20]
Fair enough, this uses a built-in function, but why is the end result so much slower when doing it yourself? The tutorials out there tell you how to use Haskell, but I don't see much help with transforming algorithms into fast code.