我正在尝试创建一个函数,使用我提供的列表(无限)显示一个数字的质因数。以下是我目前的代码:
-- Here is a much more efficient (but harder to understand) version of primes.
-- Try "take 100 primes" as an example (or even more if you like)
primes = 2 : primesFrom3 where
primesFrom3 = sieve [3,5..] 9 primesFrom3
sieve (x:xs) b ~ps@(p:q:_)
| x < b = x : sieve xs b ps
| otherwise = sieve [x | x <- xs, rem x p /= 0] (q^2) (tail ps)
-- Write a function that factors its first argument using the (infinite)
-- list of available factors given in its second argument
-- (using rem x p /= 0 to check divisibility)
primeFactsWith :: Integer -> [Integer] -> [Integer]
primeFactsWith n (p:ps) = if (rem n p /= 0) then
(primeFactsWith n ps)
else (primeFactsWith p ps)
上半部分不是我写的,但是可以正常工作。我正在尝试让下半部分工作,但它没有。请阅读代码中的注释,以更好地理解我要做什么。谢谢!顺便说一句,请不要直接给出答案。给我一些提示,告诉我如何做以及可能出了什么问题。
primes = 2 : 3 : sieve [5,7..] 9 primesFrom3 where ...
,并比较在main = print (primes !! n)
中增加n
的 内存使用(以及时间)。使用优化开关 -O2 编译成独立可执行文件运行 ($> primes +RTS -s
查看统计信息)。 - Will Ness