I\'m working my way through Real World Haskell (I\'m in chapter 4) and to practice a bit off-book I\'ve created the following program to calculate the nth prime.
<
As I said in my comment, you shouldn't be building a list by appending a single element list to the end of a really long list (your line primes' = primes ++ [test]
). It is better to just define the infinite list, primes
, and let lazy evaluation do it's thing. Something like the below code:
primes = [2, 3] ++ loop 5
where.
loop test
| isPrime primes test = test:(loop test')
| otherwise = test' `seq` (loop test')
where
test' = test + 2
Obviously you don't need to parameterize the isPrime
function by primes
either, but that's just a nit. Also, when you know all the numbers are positive you should use rem
instead of mod
- this results in a 30% performance increase on my machine (when finding the millionth prime).