我有一个关于Clojure的问题:
我正在尝试通过Project Euler学习这门语言,但是我不理解底层发生了什么:以下代码旨在返回一个列表,其中包含所有小于lim
的质数。我认为它应该是O(n)的堆空间复杂度,因为我首先创建了一个包含所有小于lim
的数字的列表,然后一边逐个过滤它们,一边将第一个移动到新列表中。(我知道实际上每次循环我都会创建新的列表,但我认为它们不会占用更多的内存?)无论如何,我正在使用以下方式运行它:
(defn getAllPrimes [lim]
(defn getPrimes [primes numlist]
(if (not-empty numlist) ;base case;
(recur (cons (first numlist) primes) ;put the prime on to the prime list
(filter
(fn [x] (not (div? x (first numlist)))) ;remove the prime and all its multiples from the numlist
(rest numlist)))
primes)); return the primes
(getPrimes () (range 2 lim))) ;call the recursive function with and empty prime list to be filled up and a full numlist to be emptied
当我调用时,我的堆空间总是不足。
(apply + (getAllPrimes 2000000))
,但我不会在
上用尽空间(apply + (filter even? (range 2000000)))
所以我认为我不理解如何在调用recur时对列表进行垃圾收集,实际上可能正在使用O(n*n)的堆或其他东西。
doall
在每一步中实现序列化。 - user445161