views:

960

answers:

2

I just have started to learn Haskell and combine reading books and tutorials with solving problems from Project Euler. I have stuck on Problem 27 because I get "C stack overflow" error using this code:

euler.hs

divisors n = [x | x <- [1..n `div` 2], n `mod` x == 0] ++ [n]
is_prime n = divisors n == [1, n]
f a b = [n^2 + a * n + b | n <- [0..]]
primes_from_zero a b = length(takeWhile is_prime (f a b))

command window

this command gives Euler's coefficients 1 and 41 (40 primes in row)

foldr (max) (0, 0, 0) [(primes_from_zero a b, a, b) | a <- [0..10], b <- [0..50]]

this one fails with "C stack overflow" (I wanted to obtain coefficients -79 and 1601 also mentioned in the problem definition):

foldr (max) (0, 0, 0) [(primes_from_zero a b, a, b) | a <- [-100..0], b <- [1500..1700]]

Would you tell me, please, why does the error arise and how to resolve it? Thank you!

I use WinHugs.

+2  A: 

I don't know why litb put his answer into a comment instead of an answer, so I'm copying it here so that people will see it:

http://www.haskell.org/haskellwiki/Stack_overflow

I think it's the right answer. But the short version is that foldr is not tail recursive.

I've marked this post as Community Wiki, so I won't get any reputation from it.

Craig Stuntz
+5  A: 
Chris Conway
Have to say foldl also gives this error, though foldl' works well. Thank you for the explanation anyway!
Alexander Prokofyev
I tried to address the foldl vs. foldl' issue above.
Chris Conway