# Haskell script once worked

This topic is 3057 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Some time ago I began tinkering with Haskell, but then I suddenly became very very busy and had to stop. Only yesterday I came back. In the meanwhile, I bought a new computer, and copied my code directory. I began solving some Project Euler problems - http://projecteuler.net/ When trying to remember how to compile and such things, I tested the first problem, which I swear worked in my old laptop. The assignment:
{-
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.
-}

My old solution:
suma :: [Integer] -> Integer
suma [] = 0
suma (x: xs) = x + suma (xs)

divisible:: Integer -> Integer -> Bool
divisible x y = ((x mod y) == 0)

main = print (suma [x | x <- [1..], x < 1000, (divisible x 3) || (divisible x 5) ])

When running this, now it gets hang, like in an infinite loop. I changed the last line so:
main = print (suma [x | x <- [1..999], (divisible x 3) || (divisible x 5) ])

And works like a charm, now. So... What's going on? My guess is that my old compiler was optimizing away the infinite list thanks to the "x < 1000", but the new one isn't capable of doing that, and checks every number to be lesser than 1000. But then, what's the point of having infinite lists? My compiler is ghc 6.4.10-1 for linux (x86), and I'm almost sure my old one was another ghc version - the one which came with Ubuntu 9.04 (also x86).

##### Share on other sites
There is no way that your first function ever worked. When you do a list comprehension with an input list that is infinite, then the result list is never finite. Calculating the sum of a non-finite will not terminate (unless you are using some kind of lazy sum, but here you are not).

Maybe previously you printed the output of the list comprehension and not the sum, and that is what you are remembering to have worked.

##### Share on other sites
Quote:
 Original post by moshesThere is no way that your first function ever worked. When you do a list comprehension with an input list that is infinite, then the result list is never finite. Calculating the sum of a non-finite will not terminate (unless you are using some kind of lazy sum, but here you are not).Maybe previously you printed the output of the list comprehension and not the sum, and that is what you are remembering to have worked.

Damn, you're right. I took off my laptop, copmiled it and it didn't work. I must have changed something after solving the problem.
Thank you.

1. 1
2. 2
3. 3
Rutin
19
4. 4
5. 5

• 10
• 14
• 30
• 13
• 11
• ### Forum Statistics

• Total Topics
631782
• Total Posts
3002338
×