伊德里斯的素数

时间:2015-05-16 15:24:56

标签: idris

在idris 0.9.17.1中,

灵感来自https://wiki.haskell.org/Prime_numbers, 我已经编写了以下用于生成素数的代码

module Main

concat: List a -> Stream a -> Stream a
concat [] ys = ys
concat (x :: xs) ys = x :: (concat xs ys)

generate: (Num a, Ord a) => (start:a) -> (step:a) -> (max:a) -> List a
generate start step max = if (start < max) then start :: generate (start + step) step max else []

mutual
  sieve: Nat -> Stream Int -> Int -> Stream Int
  sieve k (p::ps) x = concat (start) (sieve (k + 1) ps (p * p)) where
    fs: List Int
    fs = take k (tail primes)
    start: List Int
    start = [n | n <- (generate (x + 2) 2 (p * p - 2)), (all (\i => (n `mod` i) /= 0) fs)]

 primes: Stream Int
 primes = 2 :: 3 :: sieve 0 (tail primes) 3


main:IO()
main = do     
  printLn $ take 10 primes

在REPL中,如果我写take 10 primes,则REPL会正确显示[2, 3, 5, 11, 13, 17, 19, 29, 31, 37] : List Int

但是如果我尝试:exec,没有任何事情发生,如果我尝试编译和执行程序,我得到Segmentation fault: 11

有人可以帮我调试这个问题吗?

1 个答案:

答案 0 :(得分:2)

Your concat function can be made lazy to fix this. Just change its type to concat : List a -> Lazy (Stream a) -> Stream a This will do it. Note: To get all primes, change the < inside the generate function into <= (Currently some are missing, e.g. 7 and 23).