简体   繁体   English

在Haskell中过滤无限列表

[英]Filtering an infinite list in Haskell

I have the following code that implements the Sieve of Eratosthenes: 我有以下代码实现了Eratosthenes的Sieve:

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. 毫不奇怪,这会挂起,因为它必须将p与无限列表素数的每个元素进行比较。 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. ps理论上,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. 我知道如果我以2以外的其他内容开始列表会有一些问题。我仍然在努力解决这个问题,所以请不要破坏它。 Thanks ;-) 谢谢 ;-)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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