Stack space overflow when computing primes

后端 未结 3 1323
一整个雨季
一整个雨季 2021-01-06 08:58

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.

<         


        
3条回答
  •  -上瘾入骨i
    2021-01-06 09:35

    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).

提交回复
热议问题