如何在Haskell中正确使用length函数统计指定区间内的素数数量
现有代码问题与修正方案
- 首先
countPrimesUntil的辅助函数定义语法错误,你使用了while关键字,Haskell中绑定局部函数需要用where。 - 你的
countPrimes逻辑冗余错误:countPrimesUntil已经能直接返回指定区间的素数列表,统计数量直接对返回结果调用length即可,不需要额外写列表推导遍历判断。
修正后完整代码
import Data.List countPrimesUntil :: Integral a => a -> a -> [a] countPrimesUntil a b = takeWhile (<= b) $ dropWhile (< a) $ sieve [2..] where sieve (n:ns) = n : sieve [m | m <- ns, m `mod` n /= 0] -- 统计2到n区间内的素数总数 countPrimes :: Integral a => a -> Int countPrimes n = length $ countPrimesUntil 2 n -- 可选:统计任意[a,b]区间内的素数总数 countPrimesBetween :: Integral a => a -> a -> Int countPrimesBetween a b = length $ countPrimesUntil a b
测试效果
- 执行
countPrimesUntil 2 10输出[2,3,5,7],和原有功能一致 - 执行
countPrimes 10输出4,符合你需要的总数统计需求 - 执行
countPrimesBetween 3 10输出3,对应区间[3,10]内的3、5、7三个素数
内容的提问来源于stack exchange,提问作者Jeff
相关产品推荐
相关产品推荐

