I have been learning Haskell over the last few days, through Learn You A Haskell. I’ve been attempting to complete some Project Euler problems, some of which require primes. However the function I have written to try to generate some (in this case primes below 20000) isn’t outputting correctly. When I run it, GHCi returns ‘[1, ‘ and seemingly doesn’t terminate. The code I am using is:
sieve :: (Integral a) => a -> [a] -> [a]
sieve 20000 list = list
sieve n (x:xs) = sieve (n+1) $ x:(filter (\q -> q `mod` n /= 0) xs)
primesto20000 = sieve 2 [1..20000]
And then I am calling primesto20000. I understand that the function may be inefficient, I am mainly asking for help on syntactic/process errors that I must have made.
Thankyou
You’re filtering out multiples of every number, not just prime numbers. You want to check divisibility by
x, not byn. (In fact, I’m not sure you neednin thesievefunction at all; just make yourprimesto20000function generate the appropriate input list, and pass that.)