【问题标题】:Prime numbers in Idris伊德里斯中的素数
【发布时间】:2015-05-16 15:24:56
【问题描述】:

在 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

谁能帮我调试一下这个问题?

【问题讨论】:

标签: idris


【解决方案1】:

你的 concat 函数可以懒得解决这个问题。只需将其类型更改为

concat : List a -> Lazy (Stream a) -> Stream a

这样就可以了。

注意: 要获取所有素数,请将生成函数中的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-02
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    • 2015-12-30
    相关资源
    最近更新 更多