简体   繁体   中英

Filtering an infinite list in Haskell

I have the following code that implements the Sieve of Eratosthenes:

primes :: [Int]
primes = primes' [2..]

primes' :: [Int] -> [Int]
primes' [] = []
primes' (p:ps) = p:(primes' [p' | p' <- ps, not (p' `isMultiple` p)])

a `isMultiple` b = (a `mod` b) == 0

main = print (sum (primes' [2..100000]))

I would like to change main to something like

main = print (sum [p | p <- primes, p < 100000]))

Not surprisingly, this hangs because it must compare p against every element of the infinite list primes. Since I know that primes is in increasing order, how do I truncate the infinite list as soon as I find an element that exceeds my upper limit?

ps In theory, primes' filters the input list to return a list of primes. I know there will be some issues if I start the list at something other than 2. I'm still working on how to address this issue on my own, so please no spoilers. Thanks ;-)

在这种情况下,你知道一旦谓词为一个元素返回false,它就不会为后面的元素返回true,你可以用takeWhile替换filter ,一旦谓词为第一个返回false就停止获取元素时间。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM